在允许子类到catch
到Angular2中的observable之前,基类是否有可能subscribe
出现某些错误。
e.g。
export class SomeBaseClass {
constructor(private _http: Http, private _location: Location) {}
protected _fetchData(url): Observable<any> {
const headers = new Headers();
headers.append('Authorization', 'Token foo');
return this._http.get(url, {headers})
.map(response => response.json())
.catch(response => this._handle401(error));
}
private _handle401(response: Response) {
if(response.status === 401) {
this._location.go('/login');
}
// What should this return?
}
}
export class SomeClass extends SomeBaseClass {
constructor( _http: Http, _location: Location) {
super(_http, _location);
}
doTheThing() {
this._fetchData('/someUrl')
.subscribe(
response => this._handleResponse(response),
error => this._handleErrorThatIsNot401(error));
}
private _handleResponse(response) {
// ...
}
private _handleErrorThatIsNot401(error) {
// ...
}
}
catch
我想要的是什么?我应该使用map
(或其他)吗?或者我完全以错误的方式解决这个问题?
这两个答案(到目前为止)都让我走上正轨,最终 - 我解决了这个问题:
protected _get(url: string, data?: any): Observable<any> {
return super._get(url, data, this._authorizationHeader)
.map(response => response.json())
.catch(response => this._handle401(response));
}
private _handle401(response: Response): Observable<any> {
try {
if(response.status === 401) {
this._router.navigateByUrl('/login');
return Observable.throw(response.status);
}
} catch(err) {
console.warn('AuthenticatedHttpService._handle401');
console.error(err);
}
return Observable.of(response);
}
答案 0 :(得分:5)
单独使用catch
并没有多大帮助,因为您订阅了客户端代码,并且必须从Observable
返回catch
。
我会按如下方式实现它:
Rx.Observable.of(42)
.do(v=>{throw new Error('test')})
.catch(Rx.Observable.of(undefined))
.filter(v=>{return v !== undefined})
.subscribe(
(e)=>{console.log('next', e)},
(e)=>{console.log('error', e)},
()=>{console.log('complete')}
);
答案 1 :(得分:2)
.catch()
是正确的。
Observable
很懒,所以在订阅之前没有错误。不确定你是否意味着这种“之前”因此我提到它只是为了确定。