angularrxjsobservableswitchmap

Angular - Integrate initial values and filters values in async pipe


I have this function that return an Observable's list of 'streets' by passing it city id:

getStreetsByCityId(id: number)

And it's the template:

<input type="text" [formControl]="search">
<ol>
  <li *ngFor="let s of list | async">{{s.name}}</li>
</ol>

Now, in this way i can initial the list:

this.list = this.mdSvc.getStreetsByCityIdObs(1)

And in this way i can handling the filter of the list:

 this.list  = this.search.valueChanges.pipe(
  filter(val => val),
  switchMap(val => this.mdSvc.getStreetsByCityIdObs(val))
);

What I am missing is how to do the two actions together: initial the list with values and also handling filter. I can not run the two actions one after one, because they will override each other.

My question is actually how to both initialize the list and also support the filters together?


Solution

  • Ok i got it. I just had to add 'startWith' operator:

    this.list  = this.search.valueChanges.pipe(
      startWith(1),
      switchMap(val => this.mdSvc.getStreetsByCityIdObs(val))
    );