I had this code
return this.http.get(this.pushUrl)
.toPromise()
.then(response => response.json().data as PushResult[])
.catch(this.handleError);
I wanted to use observable
instead of Promise
how can i return the error to the calling method?
What's the equivalent to 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);
}
}
the calling method was:
getHeroes() {
this.pushService
.doSomeGet();
// .then(pushResult => this.pushResult = pushResult)
// .catch(error => this.error = error);
}
How to Convert an Observable to a Promise in Angular? Since the get method of HttpClient returns an observable, we use the toPromise() method to convert the observable to a promise. Since you can convert an observable to a promise, you can make use of the async/await syntax in your Angular code.
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time.
A promise is a JavaScript object which is responsible for handling callbacks and other asynchronous events or data with 2 different possible states, it either resolves or rejects. The Promise. reject() method is used to return a rejected Promise object with a given reason for rejection.
Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.
private handleError(error: any) { // previously // return Observable.throw('Some error information'); // now return throwError('Some error information'); }
See also How to catch exception correctly from http.request()?
With RxJS 6 Observable.throw()
has changed to throwError()
Observable.throw(new Error()); // becomes throwError(new Error());
Source: RxJS v5.x to v6 Update Guide - Depracations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With