如何在Angular 4.3+中全局设置{观察:'响应'}选项? [英] How to set the { observe: 'response' } option globally in Angular 4.3+?
问题描述
首先想到的是使用 HttpInterceptor
,但是 clone(...)
方法的签名不包含 observe
选项.除了为每个请求定义 {遵守:'response'}
选项之外,我没有看到替代的还 ...
The first thought was to use an HttpInterceptor
but the signature of the clone(...)
method does not contain the observe
option. Other than defining the { observe: 'response' }
option for each request, I don't see an alternative yet ...
因此,有没有一种方法来设置 {观察:'response'}
选项全局,例如通过 HttpInterceptor
?
So, is there, if any, method to set the { observe: 'response' }
option globally, e.g. via the HttpInterceptor
?
clone(update: {
headers?: HttpHeaders;
reportProgress?: boolean;
params?: HttpParams;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
withCredentials?: boolean;
body?: T | null;
method?: string;
url?: string;
setHeaders?: {
[name: string]: string | string[];
};
setParams?: {
[param: string]: string;
};
}): HttpRequest<T>;
推荐答案
我知道这个问题很老但是很有趣.
I know the question is old but very interesting.
我考虑了httpClient方法的覆盖.
I thought about the overridden of the httpClient Methods.
您只需要重写一次方法.并且所有工作都将完成.
You just need to override the methods once. And all of the work will be done.
像这样的GET方法示例:
something like this for example for GET Method:
overrideGetRequest() {
const httpRequest = this.http.get.bind(this.http);
this.http.get = function get<T = any>(url: string, options?: any): Observable<T> {
let requestOptions = options || {};
if(!('observe' in requestOptions)) {
requestOptions = { ...requestOptions, observe: "response" };
}
return httpRequest(url, requestOptions);
};
}
这是Stackblitz示例,在此示例中,我重写了httpClient的POST和GET方法.
And here is the Stackblitz example, where I have overridden the POST and GET methods of the httpClient.
https://stackblitz.com/edit/angular-interceptors-kknew1?file=app%2Fapp.component.ts
这篇关于如何在Angular 4.3+中全局设置{观察:'响应'}选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!