how to use switchMap to cancel pending http requests and taking the last subscribe only?

后端 未结 3 1545
礼貌的吻别
礼貌的吻别 2021-01-19 05:11

i tried canceling pending http request using subscription.unsubsribe like this:

getAgentList(pageNumber: number, filter: string): any {
   let requestUrl: s         


        
3条回答
  •  鱼传尺愫
    2021-01-19 05:29

    Looks like the problem is that the subscription is done after the next. Think of it like addEventListener on the DOM. You receive events after you add the listener, or in this case, the subscriber.

    getAgentList(pageNumber: number, filter: string): any {
        let requestUrl: string = ‘...’
    
        // assuming this.$filter is a Subject
        // subscription to it first
        this.$filter.switchMap(requestUrl => this.backEndCommService.getData(requestUrl))
            .subscribe(
                (res: any) => {
                    let serverResponse: ServerResponse = new 
                    ServerResponse(this.accountId, pageNumber, 
                    res.search_results, 
                    res.resultRows, res.pageSize, res.resultPages)
                    this._agentListData$.next(serverResponse);
                },
               (err: HttpErrorResponse) => {
                    console.log('handling error')
               }
        );
    
        // then call next()
        this.$filter.next(requestUrl)
    }
    

    That’s probably it. Unless, this.$filter is a BehaviorSubject or ReplaySubject, then we may have a different problem.

提交回复
热议问题