Search code examples
angulartypescriptrxjsangular-httpclient

Piping inside a pipe voids tapping in the outer one in RXJS during a get call in Angular


I noticed that some of my tap(...) invokations won't log to console, so I investigated further and found that an inner piping seems to kill off the outer piping. For instance, the code below, will show inner but won't show outer.

return this.http.get<{ token: string }>(url)
  .pipe(

    tap(_ => console.log("outer")),

    switchMap(_ => {
      ...
      return of(id);
    }),

    catchError(_ => {

      const urlLocal = url.replace(domainProd, domainDev);
      return this.http.get<{ token: string }>(urlLocal)
        .pipe(

          tap(_ => console.log("inner")),

          switchMap(_ => {
            ...
            return of(id);
          })

        );
    })
  );

I'm not sure I understand how to explain it nor how to infer this behavoir from the docs for tap. As far I figure, the tapping is piped to occur prior to the call invokation and, hence, prior to any error being detected.

Apparently, I'm mistaken somehow but I'd like to see it documented or explained somehow and, obviously I failed to find that information too.

As for the structure, if it's surprising, we have an environment on the server that works with the outer and, if run locally, fails, switching to the inner one. Finally, I'm getting a token from which I'm getting sub only, switching the map to the simple string and returning it as an observable.


Solution

  • The tap operator takes up to 3 callbacks. The first one is called in case a (success) value is emitted, but not when the observable goes in error. Try this as your first tap operator:

     tap( 
       result => console.log("outer next", result), 
       err => console.log("outer error", err), 
     )
    

    In case your first http call fails, you should see a log of "outer error" before any code inside your catchError operator is called.

    Assuming your are learning the latest RXJS 6, I would recommend using rxjs.dev as your first source of reference. (Thanks to @DeborahK for that link).
    The site that you referred to www.learnrxjs.io has a nice primer, but once you get the basic concepts I find its documentation of operators too limited. The official rxjs.dev site documents their full interface, describes their behaviour also for edge cases, and typically provides a similar number of code samples.