30

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);
}
Elad Benda
  • 32,996
  • 80
  • 259
  • 444
  • The above code with ``Promise.reject`` uncommented works perfectly fine. I am not sure why. Do you have any thoughts on it? – raj Nov 15 '16 at 22:39

2 Answers2

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

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
23

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

MHX
  • 1,533
  • 2
  • 22
  • 30