Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 4如何为整个应用程序设置HttpClient的默认选项?_Angular - Fatal编程技术网

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

Angular 4如何为整个应用程序设置HttpClient的默认选项?,angular,Angular,我想对我的整个Angular 4应用程序使用相同的请求选项。特别是,我希望通过credentials:environment.xhrWithCredentials传递请求的(基于当前环境) 但我不认为像这样为每个请求设置选项是一个好主意: this.http.get('/api', {withCredentials: environment.xhrWithCredentials}) 有没有办法为整个应用程序设置一次HttpClient的默认选项?您可能需要使用全局服务“ApiService”

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

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

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

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

您可能需要使用全局服务“ApiService”

公共getApi(端点:字符串):可观察{ 返回此.http.get('/api/'+endpoint,{withCredentials:environment.xhrWithCredentials}); }

然后注入此ApiService而不是Http,并使用所需的端点调用getApi()。

我还没有使用它,但基于此,您需要拦截所有请求并在那里设置基本属性

@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);
    }
}
@Injectable()
导出类AuthInterceptor实现HttpInterceptor{
构造函数(){}
截取(req:HttpRequest,next:HttpHandler):可观察{
const authReq=req.clone({withCredentials:true/*environment.xhrWithCredentials*/});
返回next.handle(authReq);
}
}

您可以很好地考虑使用角度httpInterceptor。。您始终可以覆盖默认的Http实现。@Injectable()导出类HttpInfrapiService扩展了Http{…},但这不是意味着我应该为每个Http方法创建类似的函数吗?更新了我的答案