我正在关注此链接here上的教程。
作者在这里做了一些我不太了解的事情。在catchAuthError方法中,他将服务自己的实例作为self
传递,但他不在方法本身中使用该变量。
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 (backend: XHRBackend, options: RequestOptions) {
let token = localStorage.getItem('auth_token'); // your custom token getter function here
options.headers.set('Authorization', `Bearer ${token}`);
super(backend, options);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('auth_token');
if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
if (!options) {
// let's make option object
options = {headers: new Headers()};
}
options.headers.set('Authorization', `Bearer ${token}`);
} else {
// we have to add the token to the url object
url.headers.set('Authorization', `Bearer ${token}`);
}
return super.request(url, options).catch(this.catchAuthError(this));
}
private catchAuthError (self: HttpService) {
// we have to pass HttpService's own instance here as `self`
return (res: Response) => {
console.log(res);
if (res.status === 401 || res.status === 403) {
// if not authenticated
console.log(res);
}
return Observable.throw(res);
};
}
}
在评论中说:
我们必须将HttpService自己的实例作为
传递给我们self
为什么这是必要的,如何在这种情况下发现错误?什么是正确的方法?
答案 0 :(得分:2)
否则
return super.request(url, options).catch(this.catchAuthError(this));
或
return super.request(url, options).catch(this.catchAuthError.bind(this));
或
return super.request(url, options).catch((err)=>this.catchAuthError(err));
实际上是一样的,你在最后2个中创建一个闭包,在第一个中你给出了引用你的组件的this
。但你是对的,在这种情况下它是不必要的,因为它没有被使用。
res
中的return (res: Response) => {
等于我的第三个示例中的错误对象。
this
实例,但在我看来,这只是一个令人困惑的例子,可以简化为:
return super.request(url, options).catch((error)=>this.catchAuthError(error));
private catchAuthError (error) {
if (error.status === 401 || error.status === 403) {
// if not authenticated
console.log(error);
}
return Observable.throw(error);
};
}