【问题标题】:Can't use services inside a catchError function无法在 catchError 函数中使用服务
【发布时间】:2019-01-31 21:08:06
【问题描述】:

我想要一种处理异常的通用方法,特别是从后端收到的 401。当我不提取 catchError 内容时,它工作正常。但是,如果我只是将其提取到特定函数中,则不会在该函数中注入任何内容:

return this.http.request<T>(new HttpRequest('POST', this.appConfig.baseApiPath + url, file, {
            reportProgress: true,
            headers: headers,
            params: urlParams
        })).pipe(
            catchError((err) => {
                if (err.status === 401) {
                    this.router.navigateByUrl('/login?expired=true');
                }
                return Observable.throw(err || 'Server error')
            })
        );

这行得通!但是我想在一个函数中处理这个重定向代码,以便通过其他方法重用它。

在这里我将它导出到一个函数中:

    return this.http.request<T>(new HttpRequest('POST', this.appConfig.baseApiPath + url, file, {
        reportProgress: true,
        headers: headers,
        params: urlParams
    })).pipe(
        catchError(this.handleHttpError),
    );

handleHttpError(error: HttpErrorResponse) {
    if (error.status === 401) {
        this.router.navigateByUrl('/login?expired=true'); --> router is null!
    }
    return Observable.throw(error || 'Server error')
}

如果我使用这种工作方式,这就是路由器(以及其他构造函数注入服务)为空的地方......你能建议为什么吗?

【问题讨论】:

标签: angular typescript rxjs


【解决方案1】:

原因是您失去了上下文。当函数以这种方式声明时,this 关键字是关于函数的范围,而不是整个类。为了不丢失上下文,您应该使用箭头函数:

handleHttpError = (error: HttpErrorResponse) => {
    if (error.status === 401) {
        this.router.navigateByUrl('/login?expired=true');
    }
    return Observable.throw(error || 'Server error')
}

【讨论】:

    【解决方案2】:

    更好的方法是将“this”绑定到您的呼叫:

    catchError(this.handleHttpError.bind(this))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多