• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

我可以在“subscribe”:前捕获某些错误吗在Angular2的RXJS可观察

用户头像
it1352
帮助1

问题说明

在允许子类 subscribe 到observable之前,基类是否有可能 catch 某些错误Angular2。

Is it possible for a base class to catch certain errors before allowing the subclass to subscribe to the observable in Angular2.

例如

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) {
        // ...
    }
}

赶上我在找什么?我应该使用 map (或其他)吗?或者我是否完全以错误的方式解决这个问题?

Is catch what I am looking for? Should I be using map (or something else)? Or am I going about this the wrong way entirely?

两个答案(到目前为止)都把我在正确的轨道上,最终 - 我这样解决了:

Both answers (so far) put me on the right track, ultimately - I solved it like this:

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);
}

正确答案

#1

.catch()是正确的。

Observable 是懒惰的,所以在订阅之前没有错误。不确定你是否意味着这种之前因此我提到它只是为了确定。

Observable is lazy, so there are no errors before you subscribe. Not sure if you mean this kind of "before" therefore I mention it just to be sure.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhchbbei
系列文章
更多 icon
同类精品
更多 icon
继续加载