Reputation: 1038
One of the methods in an angular service returns an Observable that a component is subscribed to. But in that method there is a promise that is returned as well and I want to be able to catch that in case it returns a reject. Find piece of code below:
return this.http.get(url)
.map(res => res.json())
.map((data: any) => {
try {
if (data === "14") {
this.nativeService.set(value)
.then(() => {
console.log('ok');
})
.catch((err) => { throw new Error(); //error that I want to catch
})
}
}
catch (err) {
throw new Error();
}
return data;
})
.catch((err) => this.handleError(err));
This nativeService is currently mocked which returns the following
set(value: any): Promise<any> {
return new Promise((resolve, reject) => {
reject('');
})
}
The data is returned though. Then the error is thrown and I am not being able to catch it in order to call the method handleError(). I understand that promise is an asynchronous call. Can someone advise on how to re-arrange the code in order to catch an error returned by the service.
Thanks, Ashley
Upvotes: 2
Views: 1521
Reputation: 2081
This is not how you return a data from an observable. You cannot use a simple return data
kind of statement here. Also you are already returning an observable so where do you expect this data will go?
For data to be returned you actually create a new observable and put an observer on the received data.
Let me correct your code:
return Observable.create((observer) => {
this.http.get(url)
.map(res => res.json())
.subscribe((data) => {
if (data === "14") {
this.nativeService.set(data)
.then(() => {
console.log('ok');
observer.next(data);
})
.catch((err) => {
observer.next(err); // Error thrown if some problem in promise.
})
}
},(err) => {
observer.error(err); //Error thrown if problem in http.get().
});
Now the component you have subscribed from will have 3 outputs. 1. data 2. Promise error (Both of 1 and 2 in .subscribe
's data) and 3. http.get()
error. Accordingly you have to manage there.
NOTE: I have solved only the problem mentioned in question. I am not sure about the part that I do not know like -
if(data === "14")
- Here it seems like you want to compare it with number 14 and not string "14". this.nativeService.set(data)
- Assuming this promise returns everything correctly.Upvotes: 2