在我的angular应用程序(angular版本5)中,我使用的是来自@angular/http的Http。另外,我还以一种正常的方式添加了报头,比如
getHeaders(){
let headers = new Headers();
headers.append('authorization', 'Bearer '+this.authToken);
headers.append('Content-Type', 'application/json');
return headers;
}现在我想改变这种方式,并考虑使用HttpInterceptor。据我所知,我们必须在HttpClient中使用它,但在我的angular应用程序中。到目前为止,我已经使用了Http。我们有没有办法用Http来实现HttpInterceptor。
发布于 2019-01-10 17:45:57
以下是如何使用Http模块模拟Http拦截器。
// create interceptor service
import { Injectable } from '@angular/core';
import {
Http,
ConnectionBackend,
RequestOptions,
RequestOptionsArgs,
Response,
Headers,
Request
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { environment } from '../../environments/environment';
// Shows Progress bar and notifications
import { NotifyService } from "./loader";
@Injectable()
export class HttpInterceptor extends Http {
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private notifyService: NotifyService
) {
super(backend, defaultOptions);
}
// for get method
get(url: string, options?: RequestOptionsArgs): Observable<any> {
this.beforeRequest();
return super.get(this.getFullUrl(url), this.customizeOptions(options))
.catch(console.log('Ouch!!!'))
.do((res: Response) => {
console.log('Nothing can stop me');
}, (error: any) => {
console.log("I'm hit. where's my medicccc : - X");
})
.finally(() => {
console.log('Finally we Won the war :-)')
});
}
// write for post method here
// some other methods you can write here
// to handle error
private onError(error: any): void {
this.notifyService.popError();
}
private onFinally(): void {
this.responseInterceptor();
}
}
现在在app.module中执行以下操作:(请注意: HttpInterceptor是从您创建的文件导入的)
providers: [
NotifyService,
{
provide: HttpInterceptor,
useFactory:
(backend: XHRBackend, defaultOptions: RequestOptions, notifyService: NotifyService) => {
return new HttpInterceptor(backend, defaultOptions, notifyService);
},
deps: [ XHRBackend, RequestOptions, LoaderService, Store]
}并修改您的服务文件:
/ imports here
// .......
@Injectable()
export class DataService {
constructor(public http: HttpInterceptor) {};
getData() {
return this
.http.get(`data?limit=20&offset=40`)
// will hit the api on http://api.localhost.com:4000/data?limit=20&offset=40
.map(res => res.json().data)
}
}https://stackoverflow.com/questions/54125311
复制相似问题