【问题标题】:Cancel pending $http request取消挂起的 $http 请求
【发布时间】:2018-09-24 17:49:37
【问题描述】:

我开始使用 Angular 6 和 Web API 开发单页应用程序。我有一个搜索框,用于搜索按键事件的数据。我看到首先加载旧响应的行为,然后是在慢速连接上看起来不太好的下一个响应。每次使用新字符或更少字符触发 key up 时,如何取消挂起的搜索请求。

【问题讨论】:

标签: angular typescript


【解决方案1】:

要取消正在进行的请求,您可以取消订阅 observable。更好的是,如果您使用 switchMap 运算符,它会为您执行此操作。

【讨论】:

    【解决方案2】:

    如果您使用 observable 发出 http get 请求,您可以在发出新请求之前取消对先前 http 请求的订阅,即在您的案例中的每个 keyup 上。 在下面的示例中,假设 MyCustomSearchService 是一个服务,其方法为 getSearchResult(searchText),它返回一个 http 响应,即 return this.http.get(this.apiCallURL+searchText)

    export class MySinglePageAppComponent{
        private searchSubscription:any;//property that will store the search http subscription
        private searchText:string;//search text binded to your text box
        constructor(private myCustomSearchService: MyCustomSearchService) 
        {}
        //function called upon keyup
        getSearchValue(){
            //if already searched something then cancel its subscription.
            if(this.searchSubscription){
                this.searchSubscription.unsubscribe();
            }
            this.searchSubscription=this.myCustomSearchService.getSearchResult(this.searchText).subscribe((response)=>{
             let resultJSON=JSON.parse(response.json())
             //rest of the search hadler logic here
          });
        }
    }
    

    这样,之前的待处理请求就会被取消。

    【讨论】:

      【解决方案3】:

      您可以使用 KeyUp/KeyDown 事件来触发事件;在事件取消订阅请求设置为可观察。

      KeyUp/KeyDown https://angular.io/guide/user-input

      退订:

      let sub = this.http.get(url, {headers: reqHeaders})
              .subscribe(
                  (res) => {
                      ...
                  }
              );
      
      sub.unsubscribe();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-18
        • 2018-02-14
        • 1970-01-01
        • 2014-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        相关资源
        最近更新 更多