2017-08-17 54 views
1

我想为我的整个Angular 4应用程序使用相同的请求选项。特别是我想通过withCredentials: environment.xhrWithCredentials请求(基于当前环境)。Angular 4如何为整个应用程序设置HttpClient的默认选项?

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

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

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

+0

你能想到的采用了棱角分明httpInterceptor参考[本条](https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462) –

+0

嗯..你总是可以覆盖默认的HTTP实现的。 – Arun

+0

@Injectable() export class HttpInfraAPIService extends Http {....} – Arun

回答

1

我还没有使用它,但基于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); 
    } 
} 
+0

已更新我的回答 –

+0

完全像这样,谢谢。很好! –

0

你可能想使用一个全球性的服务“ApiService”

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

再注入这ApiService而不是HTTP和你想要的端点调用getApi()。

+0

但这并不意味着我应该为每个http方法创建类似的函数吗? –

相关问题