【问题标题】:What's the observable equivalent to `Promise.reject``Promise.reject` 的可观察等效项是什么
【发布时间】:2016-12-23 22:46:46
【问题描述】:

我有这个代码

    return this.http.get(this.pushUrl)
        .toPromise()
        .then(response => response.json().data as PushResult[])
        .catch(this.handleError);

我想使用observable 而不是Promise

如何将错误返回给调用方法?

Promise.reject 的等价物是什么?

    doSomeGet() {
        console.info("sending get request");

        this.http.get(this.pushUrl)
            .forEach(function (response) { console.info(response.json()); })
            .catch(this.handleError);
    }

    private handleError(error: any) {
        console.error('An error occurred', error);
        // return Promise.reject(error.message || error);
    }
}

调用方法是:

getHeroes() {
    this.pushService
        .doSomeGet();
        // .then(pushResult => this.pushResult = pushResult)
        // .catch(error => this.error = error);
}

【问题讨论】:

  • 上面带有Promise.reject 未注释的代码工作得很好。我不确定为什么。你有什么想法吗?

标签: http angular promise observable


【解决方案1】:
private handleError(error: any) {
    // previously 
    // return Observable.throw('Some error information');

    // now
    return throwError('Some error information');
}

另见How to catch exception correctly from http.request()?

【讨论】:

  • 这种方法在 RXJS 中似乎已被弃用...更喜欢使用 throwError 运算符:here the documentation
  • 已弃用。
【解决方案2】:

使用 RxJS 6 Observable.throw() 已更改为 throwError()

Observable.throw(new Error());

// becomes

throwError(new Error());

来源:RxJS v5.x to v6 Update Guide - Depracations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多