1

On an Angular 5 app I'm working on, I have to manually trigger an error for an observable. I have already looked at a similar question here, but without result. The function with the Observable has two nested observables (getSubscription in the example).

Here is a small example on Plunker (link).
My code is inside app.component.ts. triggerError and getSubscription are the key elements. The Important part are the two nested and dependent subscriptions. For simplicity I use the same call for both subscriptions, these should be placeholders for two nested subscriptions, in a real app these will be two different subscriptions

Whether an error is thrown or a successful response is sent, the subscription always jumps to the method with the successful outcome. How is it possible that the subscription will jump to the corresponding method in case of an error?

The structure with the two nested and interdependent subscriptions is very important and must be considered when proposing a solution!

4
  • Where is the code? Commented Apr 16, 2018 at 7:46
  • @Melchia There is a link to plunker in the question Commented Apr 16, 2018 at 7:49
  • your code actually seems weird. why are you subscribing again to the same this.earthquakeService.getRecentEarthquakes method inside the map function on it? Commented Apr 16, 2018 at 7:51
  • @GHB I edited my question according to your point Commented Apr 16, 2018 at 7:58

2 Answers 2

1

If you are using angular 5 , then you better to use HttpClient instead of Http. Then you can use of pipe for your http method and write catchError function inside it.

Read this article

Note 1. if you'r client origin ( which is localhost:4200 ) is different as your server origin then you have to use angular proxy to receive appropriate error from the server.

Read How to set proxy on an angular Cli project

And finally to customize and translate you'r errors you can use a function into you'r service like below .

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an ErrorObservable with a user-facing error message
  return new ErrorObservable(
    'Something bad happened; please try again later.');
}; 

Which will call from the HttpClient pipe. like below

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      catchError(this.handleError)
    );
}

Hope it help.

Sign up to request clarification or add additional context in comments.

Comments

1

I think your getSubscription function is incorrect. you can simply change that to something like this:

getSubscription(): Observable<boolean> {
        return this.earthquakeService.getRecentEarthquakes().map((recent) => {
            if(false) {
                return true;
            } else {
                console.log('error thrown');
                throw Observable.throw('ERROR');
            }
        });
    }

when you use map on and observable, at the end you're returning another observable. and later you can subscrbe to the result. no need to subscribe inside the map again

Update:

If you want to work with two different observables, you can work it by chaining them together like this:

getSubscription(): Observable<boolean> {
        return this.earthquakeService.getRecentEarthquakes().map((recent) => {
            // doing something with "recent" 
        }).switchMap((recent)=>{
          // you can use some condition here to either use the inner observable,
          // or return some other observable. just remember that you should return 
          // `Observable` here. this is the inner observable:
              return this.earthquakeService.getRecentEarthquakes()
            }).map((next) => {
                    if(false) {
                    return true;
                } else {
                    console.log('error thrown');
                    throw Observable.throw('ERROR');
                }
                });
        }

6 Comments

in this example, you only have one subscription. The nested and dependent aspect is pretty important to me
what's your usage exactly for that other nested subscription?
Unlike the example, there are two different subscriptions/observables. Depending on the result of the first subscription, subscription number two is called. if an error occurs in this second subscription, this number should be raised to the top.
so you mean inside the triggerError function, you want to subscribe to the result from the nested observable?
I want to subscribe to the result of the higher subscriptio which is depending on the innner one.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.