【问题标题】:Angular2 catch request errorAngular2 捕获请求错误
【发布时间】:2016-09-16 00:01:06
【问题描述】:

我有一个获取请求的代码。它正在编译和工作,但我在控制台中有错误。

public get<T>(url: string, headers: Headers = this.jsonHeaders()): Observable<T> {
        return this._http.get(url, { headers: headers })
                   .catch((err: Response, caught: Observable<T>) => {
                       if (err.status === 401) {
                           this._router.navigate(["/auth/login"]);
                           return Observable.throw("401 Unauthorized");
                       }
                       return caught;
                   })
                   .map(res => <T>this.toJSON(res));
    }

错误:

error TS2345: Argument of type '(err: Response, caught: Observable<T>) => ErrorObservable | Observable<T>' is not assignable to parameter of type '(err: any, caught: Observable<Response>) => Observable<any>'.
  Types of parameters 'caught' and 'caught' are incompatible.
    Type 'Observable<Response>' is not assignable to type 'Observable<T>'.
      Type 'Response' is not assignable to type 'T'.

我尝试将其投射到但没有帮助

【问题讨论】:

标签: ajax angular request rxjs rxjs5


【解决方案1】:

您使用以下内容:

.catch((err: Response, caught: Observable<T>) => {
  if (err.status === 401) {
    this._router.navigate(["/auth/login"]);
    return Observable.throw("401 Unauthorized");
  }
  return Observable.throw(caught); // <-----
})

【讨论】:

  • 这很好,但我在控制台中仍然有错误。
  • 你可以试试:return caught.source;
  • 我认为原因是预期的 Observable 但返回 ErrorObservable
  • 同意,但ErrorObservablesource 属性包含Observable&lt;any&gt; 类型的源可观察对象。所以它应该解决问题;-)
  • 但不是 =( 可能是因为被抓到没有源属性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多