【发布时间】:2018-08-26 14:56:53
【问题描述】:
有些服务需要有token,有些有不同的Content-Type。我应该如何在Interceptor文件中管理它们?
【问题讨论】:
标签: angular6 angular-http-interceptors
有些服务需要有token,有些有不同的Content-Type。我应该如何在Interceptor文件中管理它们?
【问题讨论】:
标签: angular6 angular-http-interceptors
您可以在拦截器函数上获取或设置所有请求标头。以下代码揭示了用于处理此更改的标头属性:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.headers.has('Content-Type'))
contentType = request.headers.get('Content-Type');
request = request.clone({
setHeaders: {
'Authorization': `Bearer ${this.auth.getToken()}`,
'Content-Type': (contentType != 'application/json' ? 'application/text' : contentType)
}
});
return next.handle(request);
}
【讨论】:
HttpClient.Get<T>(url, options) )。这是这种用法的一个示例:return this.http.get<T>(this.path, { params: this.getHttpParams(params), responseType: type, headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
content-type 以请求您的请求。否则再次检查您的请求标头定义。祝你好运!