Angular Observables and Http

前端 未结 3 1754
遇见更好的自我
遇见更好的自我 2020-12-15 10:12

I\'m having a hard time wrapping my brain around observables in Angular. I\'m coming from the world of PHP, where things are definitely not async.

I have a componen

3条回答
  •  难免孤独
    2020-12-15 10:39

    In fact, Reactive Programming allows to create asynchronous data streams. This means that you can leverage

    The HTTP support of Angular2 leverages operators (flatMap, ...) to link streams together and implement complex processing chains. This means that you can use all concepts of Reactive Programming / RxJS to make an HTTP request part of an asynchronous data stream.

    Here a simple sample that allows to execute a request based on the value of a form input (when updates occur):

    this.inputControl.valueChanges.debounceTime(500).flatMap(
      val => {
        // Execute ab 
        return this.http.get(`http://...?filter=${val}`);
      }).subscribe((data) => {
        this.places = data;
      });
    

    Operators can also allow to implement easily several issues in the context of HTTP:

    • Ensure to receive the latest when requests are executed in sequence (for example based on user input). Sample of the switchMap operator that cancels the previous in-progress requests when a new one is triggered

      this.ctrl.valueChanges.switchMap(
        val => {
          return this.http.get(`http://...?filter=${val}`);
        });
      
    • Buffer events and trigger the last one after an amount of time. Sample that waits for an inactivity of 500ms before executing the request based on the latest value of the input:

      this.ctrl.valueChanges.debounceTime(500).flatMap(
        val => {
          return this.http.get(`http://...?filter=${val}`);
        });
      
    • Retry when requests fail. Sample of retry each 500ms and within 2s

      var params = new URLSearchParams();
      params.set('placename_startsWith', searchText);
      params.set('username', 'XXX');
      
      return this.http.get('http://api.geonames.org/postalCodeSearchJSON',
            { search: params })
        .retryWhen(error => error.delay(500))
        .timeout(2000, return new Error('delay exceeded'))
        .map(res => res.json().postalCodes);
      

    Here are some articles regarding Reactive Programming that could help you:

    • The introduction to Reactive Programming you've been missing by André Staltz - https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
    • Everything is a stream by Rob Wormald - http://slides.com/robwormald/everything-is-a-stream

提交回复
热议问题