Reputation: 4252
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
Upvotes: 0
Views: 1773
Reputation: 150
return Observable.of(new MapConfiguration());
to generate an error with your object as a message
return Observable.throw(new MapConfiguration());
Upvotes: 0
Reputation: 2049
In order to have always a returning value you can wrap it as observable by using return Observable.of(new MapConfiguration());
in your catch.
Upvotes: 3