我有这个代码
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);
}
答案 0 :(得分:28)
private handleError(error: any) {
return Observable.throw('Some error information');
}
答案 1 :(得分:9)
对于RxJS 6,Observable.throw()
已更改为throwError()
Observable.throw(new Error());
// becomes
throwError(new Error());