Angular2: switchMap not canceling previous http calls

前端 未结 4 440
孤街浪徒
孤街浪徒 2021-02-01 07:40

I am trying to use switchMap to cancel any previous http calls in Angular2. The code is basically

var run = ():Observable => {
        var url = \'         


        
4条回答
  •  一向
    一向 (楼主)
    2021-02-01 08:06

    constructor(private _http:Http, private appStore:AppStore) {
    
            this.httpRequest$ = new Subject();
    
    
            this.httpRequest$
                .map(v=> {
                    return v;
            })
            .switchMap((v:any):any => {
                console.log(v);
                if (v.id==-1||v.id=='-1')
                    return 'bye, cancel all pending network calls';                
                return this._http.get('example.com)
                    .map(result => {
                        var xmlData:string = result.text()
                    });
            }).share()
            .subscribe(e => {                
            })
        ...
    

    and to push data in:

    this.httpRequest$.next({id: busId});        
    

    this works great and I can now have a single service that I can pipe all network calls through as well as cancel prior calls...

    see image below, as new calls come in, prior ones are canceled. note how I set slow network with a delay of 4sec to provide all is working as expected...

提交回复
热议问题