Angular 4 如何为整个应用程序的 HttpClient 设置默认选项?



我想对我的整个 Angular 4 应用程序使用相同的请求选项。特别是我想传递请求的withCredentials: environment.xhrWithCredentials(基于当前环境(。

但是我认为像这样为每个请求设置选项不是一个好主意:

this.http.get('/api', {withCredentials: environment.xhrWithCredentials})

有没有办法为整个应用程序设置一次HttpClient的默认选项?

我还没有使用它,但根据 https://angular.io/guide/http 您需要拦截所有请求并在那里设置基本属性。

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({withCredentials: true /*environment.xhrWithCredentials*/});
return next.handle(authReq);
}
}

您可能希望使用全局服务"ApiService">

public getApi(endpoint:string):Observable<any> {
return this.http.get('/api/'+endpoint, {withCredentials: environment.xhrWithCredentials});
}

然后注入这个 ApiService 而不是 Http,并使用你想要的端点调用 getApi((。

最新更新