1

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(
      concatMap(val=> this.request(val.city)),
    ).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?

Eranki
  • 750
  • 1
  • 11
  • 30

1 Answers1

1

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.

Andrei
  • 10,117
  • 13
  • 21
  • Fixed the problem. The issue is that my return type from the function 'request' has to be an observable. So, I used 'of ' operator over the return type and it fixed the issue. – Eranki Dec 19 '21 at 05:57