0

I am trying to create a generic service to fetch some settings from the server. When an error occurs I would like to catch this error and return a default value (locally I have a default configuration that should be used when an error occurs).

Since I am using Angular 4.3.6 I can use the new HttpClientModule.

The code:

/**
  * Fetches the map settings
  * @returns { Observable<MapConfiguration> }
  */

public getMapConfiguration(): Observable<MapConfiguration> {
  return this.http.get<MapConfiguration>(MapService.MAPSETTINGSURL)
    .catch((exception) => {
      console.warn('Could not fetch map configuration due to: ', exception);
      return new MapConfiguration();
    });
} 

This code gives the following error:

Type 'MapConfiguration' is not assignable to type 'ObservableInput<{}>'.

I am new to Observables (used to promises) and with a promise I could return a value in the catch. How can I solve this problem, so that there is always a value returned?

I would like to make the service handle the error and not the subscriber

2 Answers 2

3

In order to have always a returning value you can wrap it as observable by using return Observable.of(new MapConfiguration()); in your catch.

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

Comments

0
return Observable.of(new MapConfiguration());

to generate an error with your object as a message

return Observable.throw(new MapConfiguration());

Comments

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.