【问题标题】:What is the return type of Http.get().catch?Http.get().catch 的返回类型是什么?
【发布时间】:2017-08-15 23:47:35
【问题描述】:

我目前正在学习 Angular 2,参加 Deborah Kurata 的 Pluralsight 课程(Angular 2:入门)。到目前为止它很棒,但是,对于我的生活,我似乎无法发现我的 .catch 的返回类型应该是什么。在她的课程中,以及到目前为止我找到的每个示例中,返回类型都是空白的。

这就是我所拥有的:

getProducts(): Observable<IProduct[]> {
    return this._http.get("someurl")
        .map {.....}
        .catch(this.handleError);
}

handleError (response: Response) **/*what goes here?*/** {
    // the code in the course says Observable.throw, but chrome is
    // complaining that there is no such function. I have tracked 
    // down "static throw: typeof ErrorObservable.create;" in 
    // Observable.ts but I'm not sure what's going on here.
}

【问题讨论】:

    标签: angular typescript exception-handling rxjs angular2-observables


    【解决方案1】:

    最常见的返回类型是Observable

    准确地说,catch() 运算符的选择器函数定义为:

    (err: any, caught: Observable): ObservableInput
    

    返回的 Observable 使用支持多种返回类型的subscribeToResult 订阅(这就是为什么有ObservableInput 而不仅仅是Observable)。无论如何,查看源代码中的示例更容易,这些示例不在在线文档中,您应该能够理解它是如何工作的:https://github.com/ReactiveX/rxjs/blob/master/src/operator/catch.ts#L8

    或者看看subscribeToResult支持什么:https://github.com/ReactiveX/rxjs/blob/master/src/util/subscribeToResult.ts#L17

    【讨论】:

    • 谢谢@martin。不幸的是,源代码并没有说明太多(对我来说)。但我看到“导出函数 _catch(this: Observable, selector: (err: any, caught: Observable) => ObservableInput): Observable {. ..}. 所以,“_catch”(不是“catch”)是一个接受“this”(在 TS 中如何工作?)和选择器函数的函数。选择器函数返回 ObservableInput,而 _catch 本身返回Observable。具体来说,其中哪一个是“.catch”返回?(我也尝试返回“Observable”,但它当然抱怨缺少泛型类型。)
    • @emery.noel 你能给出导致你输入错误的确切代码吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-04
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2011-09-18
    相关资源
    最近更新 更多