How to keep observable alive after error in RxJS 6 and Angular 6

限于喜欢 提交于 2019-12-21 21:41:24

问题


Can anyone help with the scenario where this._getReactions$.next() not working whenever this.http.get(...) gets an error. I want to keep observable alive to take the next input.

private _getReactions$: Subject<any> = new Subject();

 constructor() {
  this._getReactions$
  .pipe(
    switchMap(() => {
        return this.http.get(...)
        // http request 
    }),
    catchError(error => {
      console.log(error);
      return empty();
    })
  )
  .subscribe(data => {
      console.log(data)
      //results handling
  });
 }

onClick() {
  this._getReactions$.next();
}

回答1:


If observable dies it calls it error handler and they are closed you can't send anything through them that means they are closed everything upstream from that including the interval is dead.

what if we want to live.

sheilding the main observer chain is the solution
put catch inside of switchmap whenever a request is fired switchmap creates the ajax observable and this time with the catch.
switchmap has a behavior that it says my source is not completed yet so I don't really care if the child completes I gonna keep going.

     constructor() {
          this._getReactions$
          .pipe( tap(value=>{this.loading=true; return value}),
            switchMap(() => {
                return this.http.get(...).pipe(
       catchError((error)=>this.handleError(error)))
                // http request 
            }),
          )
          .subscribe(data => {
              console.log(data)
              //results handling
            this.error=false;
           this.loading=false
          });
         }

      private handleError(error: HttpErrorResponse) {

    this.error = true;
    console.log(error)
    this.loading = false
    return empty();
  }

Live Demo

Detailed Info



来源:https://stackoverflow.com/questions/52370506/how-to-keep-observable-alive-after-error-in-rxjs-6-and-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!