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);
})
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With