I am using rxjs switchMap to get the latest form value from a subject, set a local variable and then perform a query based on that value.
Long story short I am populating select box options based on the current value of the form.
// Get current value of Record Form
this.recordFormService.recordForm$
.pipe(
switchMap(recordForm => {
// Get current Product Owner on Record Form
this.currentProductOwner = recordForm.value.ProductOwner;
// Search People
return this.recordsApiService.searchPeople$(this.currentProductOwner);
}),
catchError(err => {
console.error(`get recordForm$ failed ${err}`);
return throwError(err);
})
)
.subscribe(results => {
// Set Product Owners select box options
this.productOwners = results.data;
});
This is all working properly.
However, I also need to perform the same exact logic when a specific form value changes.
// Run the same logic when the ProductOwner value changes
this.parentFormGroup.controls['ProductOwner'].valueChanges.subscribe(val => {});
I tried putting the combineLatest operator at the top, however that only resolves when both observables have emitted at least one value.
The valueChanges
observable may not necessarily ever change, but recordFormService.recordForm$ will run at least once when the page is loaded.
Note: The result of the valueChanges
observable is a string and the result of the recordForm$
observable is a FormGroup object, they need to be processed entirely differently.
What operator can I use to achieve this requirement?
// Get latest value of all observables
combineLatest(
this.parentFormGroup.controls['ProductOwner'].valueChanges,
// Get current value of Record Form
this.recordFormService.recordForm$
)
.pipe(
switchMap(recordForm => {
// Get current Product Owner on Record Form
this.currentProductOwner = recordForm.value.ProductOwner;
// Search People
return this.recordsApiService.searchPeople$(this.currentProductOwner);
}),
catchError(err => {
console.error(`get recordForm$ failed ${err}`);
return throwError(err);
})
)
.subscribe(results => {
// Set Product Owners select box options
this.productOwners = results.data;
});
UPDATE:
I also tried merge
. However the results of both observables are entirely different (one is a formGroup and one is a string) and they both need to be processed differently.
// Get latest value of all observables
merge(
this.parentFormGroup.controls['ProductOwner'].valueChanges,
// Get current value of Record Form
this.recordFormService.recordForm$
)