Home > database >  How to call 2 observables based on an input from form field (Angular) and only subscribe once
How to call 2 observables based on an input from form field (Angular) and only subscribe once

Time:01-28

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;

CodePudding user response:

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()
}
  • Related