I have the following scenario.
- there is a form control like
get cars(): FormControl { return this.parentForm?.get('cars') as FormControl; }
- I want to subscribe to a service
getAttributes()
using the cars result as a parameter and also subscribe to any further changes listening forvalueChanges
oncars
form control - 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()
}