什么是可观察的等同于'Promise.reject`

时间:2016-08-17 10:18:51

标签: http angular promise observable

我有这个代码

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

2 个答案:

答案 0 :(得分:28)

private handleError(error: any) {
    return Observable.throw('Some error information');
}

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

答案 1 :(得分:9)

对于RxJS 6,Observable.throw()已更改为throwError()

Observable.throw(new Error());

// becomes

throwError(new Error());

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