我在角度2中创建了一个用于身份验证的拦截器。拦截器代码如下所示,
import {
Injectable
} from '@angular/core';
import {
Http,
XHRBackend,
RequestOptions,
Request,
RequestOptionsArgs,
Response,
Headers
} from '@angular/http';
import {
Observable
} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpService extends Http {
constructor(public headers: Headers,
public backend: XHRBackend,
options: RequestOptions) {
super(backend, options);
let token = localStorage.getItem('realtoken');;
console.log(token);
options.headers.set('Authorization', `Bearer ${token}`);
}
get(url: string, options ? : RequestOptionsArgs): Observable < Response > {
// this.headers=new Headers();
//this.headers.append('Content-Type','application/json');
let token = localStorage.getItem('realtoken');
if (typeof url === 'string') {
if (!options) {
options = {
headers: this.headers
};
}
options.headers.set('Authorization', `Bearer ${token}`);
}
return super.get(url, options).catch(this.catchAuthError(this));
}
private catchAuthError(self: HttpService) {
return (res: Response) => {
console.log(res);
if (res.status === 401 || res.status === 403) {
console.log(res);
}
return Observable.throw(res);
};
}
}
@Injectable()
export class EmployeeService {
private res: Response
private options: any;
constructor(private _httpService: HttpService) {
}
getEmployeeCollection(): any {
let url: string = Constants.DOMAIN + Constants.HOME_ROUTE;
console.log('url', url);
return this._httpService.get(url).map(res => res.json()).catch(this._errorHandler);
}
_errorHandler(error: Response) {
return Observable.throw(error);
}
}
有人能建议我在哪里错吗?由于我是初学者,我无法弄清楚我错在哪里。