我试图创建一个自定义的http类,它扩展了Http,就像Angular 2上的AngularJS拦截器一样。我跟着其他Stackoverflow问题和一些教程,但我总是得到同样的错误而且我不能找到解决方案。
我有以下Http拦截器:
import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
options = new RequestOptions();
let headers = new Headers();
headers.append('X-Auth-Token', 'Bearer ' + localStorage.getItem('access-token'));
options.headers = headers;
return super.request(url, options);
}
}
我已将其添加到app.module中,如下所示:
providers: [{
provide: Http,
useFactory: loadCustomHttp,
deps: [XHRBackend, RequestOptions]
}],
export function loadCustomHttp(backend: XHRBackend, defaultOptions: RequestOptions) {
return new CustomHttp(backend, defaultOptions);
}
我没有遇到任何关于此配置的错误,但是当我做任何请求时,我得到401,因为没有添加身份验证标头。样本请求可以是:
import { Http } from '@angular/http';
getExample() {
let url = this.urlBase + '/test';
return this.http.get(url);
}
非常感谢任何帮助,提前谢谢:)
答案 0 :(得分:1)
网址可以是两种不同类型之一,字符串或请求,所以
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('access-token');
if (token) {
if (typeof url === 'string') {
if (!options) {
options = { headers: new Headers() };
}
options.headers.set('Authorization', `Bearer ${token}`);
console.log('Url is string', options.headers.get('Authorization'));
} else {
url.headers.set('Authorization', `Bearer ${token}`);
console.log('Url is Request', url.headers.get('Authorization'));
}
}
return super.request(url, options);
}