1

I have the following scenario.

  1. there is a form control like get cars(): FormControl { return this.parentForm?.get('cars') as FormControl; }
  2. I want to subscribe to a service getAttributes() using the cars result as a parameter and also subscribe to any further changes listening for valueChanges on cars form control
  3. But how can I combine all of this into one subscription. I don't want to have 2
ngOnInit() {
  //getting initial value from the form 
  this.carsId = this.cars.value
  if (this.carsId) {
    this.getAttributes(this.carsId).subscribe()
  }

  //subscribing to any future changes in the form
  this.cars.value.valueChanges().pipe(
    map(result => {
      this.getAttributes(result)
    })
  ).subscribe()
}

...

get cars(): FormControl {  return this.parentForm?.get('cars') as FormControl;

RDK
  • 69
  • 4

1 Answers1

2

You can create an observable that emits both the initial value of the form and the changes by using startWith:

ngOnInit() {
  this.cars.value.valueChanges().pipe(
    startWith(this.cars.value),
    switchMap(result => this.getAttributes(result))
  ).subscribe()
}

If you need to filter out empty values, just add a filter:

ngOnInit() {
  this.cars.value.valueChanges().pipe(
    startWith(this.cars.value),
    filter(result => !!result),
    switchMap(result => this.getAttributes(result))
  ).subscribe()
}
BizzyBob
  • 12,309
  • 4
  • 27
  • 51
  • What if the `this.getAttributes(result)` in switchMap is an Observable too, and needs a subscribe. It's not working for me if I try this – RDK Jan 27 '23 at 15:30
  • `switchMap` will internally subscribe to the observable from `this.getAttributes()` and emit its emissions. What do you mean "it's not working"? – BizzyBob Jan 27 '23 at 15:34
  • Not sure what I'm doing wrong then, I have the following: `return this.getAttributes(result).pipe(map( .... ) )` inside of the `switchMap` – RDK Jan 27 '23 at 15:37
  • Please clarify what you mean by "not working"? Does it give an error? Does it emit the wrong data? – BizzyBob Jan 27 '23 at 15:40
  • 1
    Nevermind, I got it working. Your solution works, but my editor for some reason asked me to put in `async` inside the switchMap like `switchMap(async(result))`. That was the problem. I removed it and it works now :). Appreciate your help! – RDK Jan 27 '23 at 15:44