Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the observable equivalent to `Promise.reject`

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);
}
like image 779
Elad Benda Avatar asked Aug 17 '16 10:08

Elad Benda


People also ask

How do you turn an Observable into a Promise?

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.

How is Observable different from Promise?

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.

What happens when Promise is rejected?

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.

Which is better Promise or Observable?

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.


2 Answers

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()?

like image 149
Günter Zöchbauer Avatar answered Sep 20 '22 19:09

Günter Zöchbauer


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

like image 37
MHX Avatar answered Sep 19 '22 19:09

MHX