Angular http client observable pipe map

12,153

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...

Share:
12,153
fransyozef
Author by

fransyozef

SMILEUPPS-243F7D5912

Updated on June 04, 2022

Comments

  • fransyozef
    fransyozef almost 2 years

    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 strugglin how to (well at least figure out wich Rxjs function to use).

    Can somebody help me out with this?

  • fransyozef
    fransyozef over 5 years
    Ah cewl .. I will try it. If this works, then I can create some reusable helpers.
  • fransyozef
    fransyozef over 5 years
    Yes .. it worked , I have a helper export function checkServerSuccessResponse(data: Response): Observable<any> { return (data && data['success'] === true) ? of(data) : throwError("server responded false"); } so when the first condition is false, it will throw an error. if the condition is true, the data object is passed to the normal map