How can I implement timeout for angular2+ http request

前端 未结 4 1627
迷失自我
迷失自我 2020-12-01 18:22

Here is just regular request looking like that:

this.people = http.get(\'http://localhost:3000/users\')
                  .map(response => response.json()         


        
4条回答
  •  借酒劲吻你
    2020-12-01 18:34

    The return value of http.get() is an observable, not the response. You can use it like:

    getPeople() {
      return http.get('http://localhost:3000/users')
          .timeout(2000)
          .map(response => response.json());
      }
    }
    
    foo() {
      this.subscription = getPeople.subscribe(data => this.people = data)
    }
    
    // to cancel manually
    cancel() {
      this.subscription.unsubscribe();
    }
    

    See also https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timeout.md

提交回复
热议问题