Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  179] [ 1]  / answers: 1 / hits: 15850  / 6 Years ago, mon, october 29, 2018, 12:00:00

I have this in my service


  doSomething(): Observable<any> {
return this.http.get('http://my.api.com/something')
.pipe(
map((data: Response) => {
if (data && data['success'] && data['success'] === true) {
return true;
} else {
return false;
}
}
)
);
}

This works, I can subscribe to the function from my component, for example


    this.myService.doSomething().subscribe(
(result) => {
console.log(result);
},
(err) => {
console.log("ERROR!!!");
}
);

Al this already works, but I want to refactor so that I can remove


 if (data && data['success'] && data['success'] === true)

in my map. So that the map function only will be executed when I have upfront did the check. My first thought was to add a function in the pipe stack that will take the Response from the http client, check if the the conditions are good, otherwise throw an error (with throwError function). But I'm struggling how to (well at least figure out which Rxjs function to use).


Can somebody help me out with this?


More From » angular

 Answers
66

Try using this :



doSomething(): Observable<any> {

return this.http.get('http://my.api.com/something')
.pipe(
mergeMap((data: Response) => {
return of(data && data['success'] === true)
}
));
}


You have to perform the mergeMap first to do the check as your observable result will not be available if not...


[#53222] Thursday, October 25, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;