Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs subject switchmap http error

I'm using Subject, switchMap and .next() to cancel previous pending http calls when a new http.get() request is fired.

The problem is when i handle a http error (like timeout) the method _postMPCHC.next(...) called in html do not work anymore... Do i need to recreate the subscription on error ? How ?

import {Component} from '@angular/core';
import {NavController, NavParams, Toast} from 'ionic-angular';
import {Http, URLSearchParams} from '@angular/http';
import {AppSettings} from '../../appSettings';
import {Subject} from 'rxjs/Subject';


@Component({
  templateUrl: 'build/pages/video/video.html'
})
export class VideoPage {
  _postMPCHC: any= new Subject();

  constructor(private http: Http, private nav: NavController) {
    this.defineHttp();
  }

  defineHttp() {

    var sub = this._postMPCHC.switchMap((x: string) => {
      let params: URLSearchParams = new URLSearchParams();
      params.set('token', AppSettings.API_TOKEN);
      params.set('prog', 'mhz');
      params.set('prog', 'mpchc');
      params.set('action', x);

      return this.http.get(AppSettings.API_ENDPOINT, { search: params })

    }).timeout(5000, new Error('timeout exceeded')).subscribe(x => { },
      error => {
        let toast = Toast.create({
          message: 'Server response: ' + <any>error,
          duration: 3000,
          position: 'middle'
        });
        this.nav.present(toast);
      })

  }
}
like image 259
Zaphod Avatar asked Nov 09 '22 11:11

Zaphod


1 Answers

The problem is that when stream gets an error - it ends. If you want to handle the http error but keep main stream alive, you should handle error on the level of http stream. See this article - Error handling. What to do when error kills stream.

So, in your case you can handle error at return this.http.get(AppSettings.API_ENDPOINT, { search: params }) line by adding .pipe(catchError(...)) - it will keep your mai stream alive and will catch http errors

like image 152
dsych Avatar answered Nov 15 '22 06:11

dsych