简体   繁体   中英

concatMap is not subscribing for the second time

I am implementing concatMap operator. Even before doing that I tried making two subscriptions one after the other and it worked. The first subscription is made to the input field of form and the second subscription is made for the http request. Below is the code:

// AfterViewInit implementation
// this.form is a formGroup with formControl city

  ngAfterViewInit() {
    this.form.valueChanges.pipe(
      map (val=>val.city),
    ).subscribe(
      val => {this.request(val)}
    );
  }

   request(city){
    this.httpClient.get(url, {params:{
    ...
    }}).subscribe(
      value => {

      }, error => {}
    );
  }

The above snippet will make http call for each and every time the input field is updated. I modified the ngAfterViewInit as follows by adding concatMap:

  ngAfterViewInit() {
    this.form.valueChanges.pipe(
      map (val=>val.city),
      concatMap(val=> this.request(val)),
    ).subscribe();
  }

Now, the requests are not made as expected. The request is made only once for the first time when the input is changed. The second request is never made for the updated input field. What am I doing wrong here?

try fixing request function like this:

request(city){
    return this.httpClient.get(url, {params:{
    ...
    }}).pipe(tap(
      value => {

      }, error => {}
    ));
  }

with this fix there will be only one subscribe call in all the chain and operators will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM