【发布时间】:2019-10-06 16:29:04
【问题描述】:
我已将我的 Angular 应用程序从 4 升级到最新版本 7。经过这么多错误后,我终于让它工作了,但现在有一个问题:服务无法正常工作,就像它在控制台中没有给出任何错误但没有也能正常工作。
我认为问题在于我的 Http 拦截器和我缺少某些东西的工厂。
谁能告诉我到底是什么问题?
Http拦截器
constructor(
backend: HttpBackend,
private store: Store<any>,
private spinnerService: SpinnerService
) {
super(backend);
}
request( url: string | HttpRequest<any>, options?: any): Observable<any> {
this.showLoader();
return this.tryCatch(super.request(this.getRequestOptionArgs(options)))
}
get(url: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(super.get(url));
}
post(url: string, body: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(
super.post(url, body)
);
}
put(url: string, body: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(
super.put(url, body)
);
}
delete(url: string, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(super.delete(url));
}
patch(url: string, body: any, options?: any): Observable<any> {
url = this.updateUrl(url);
return this.tryCatch(
super.patch(url, body)
);
}
private updateUrl(req: string) {
return environment.origin + req;
}
private getRequestOptionArgs(options?: any): any {
if (options.headers == null) {
options.headers = new HttpHeaders();
}
options.headers.append('Content-Type', 'application/json');
options.headers.append(
'Authorization',
` Bearer ${sessionStorage.AccessToken}`
);
return options;
}
private tryCatch(obs: Observable<any>) {
return obs.pipe(catchError((error: HttpResponse<any>, caught) => {
if (error.status === 401 && sessionStorage.AccessToken) {
sessionStorage.clear();
this.store.dispatch({type: 'LOGOUT'});
}
this.hideLoader();
return observableThrowError(error);
}));
}
Http 工厂
export function httpFactory(xhrBackend: HttpXhrBackend, store: Store<any>, spinnerService: SpinnerService): HttpClient {
return new InterceptedHttp(xhrBackend, store, spinnerService);
}
应用模块中的提供者
{
provide: HttpClient,
useFactory: httpFactory,
deps: [HttpXhrBackend, Store, SpinnerService]
},
每当我登录时,它就会开始加载,没有其他内容,没有错误或任何内容,当我在应用模块中注释掉提供程序时,它会显示“404 未找到错误”。
有什么帮助吗?
谢谢
【问题讨论】:
标签: angular typescript http service angular-http-interceptors