【发布时间】:2019-08-12 20:19:54
【问题描述】:
我正在使用 rxjs switchMap 从主题中获取最新的表单值,设置一个局部变量,然后根据该值执行查询。
长话短说,我正在根据表单的当前值填充选择框选项。
// 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;
});
一切正常。
但是,当特定表单值发生变化时,我还需要执行相同的逻辑。
// Run the same logic when the ProductOwner value changes
this.parentFormGroup.controls['ProductOwner'].valueChanges.subscribe(val => {});
我尝试将 combineLatest 运算符放在顶部,但是只有在两个可观察对象都发出至少一个值时才能解决。
valueChanges observable 不一定会改变,但 recordFormService.recordForm$ 将在页面加载时至少运行一次。
注意:valueChanges observable 的结果是一个字符串,recordForm$ observable 的结果是一个 FormGroup 对象,它们需要完全不同的处理方式。
我可以使用什么运算符来实现这个要求?
// 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;
});
更新:
我也试过merge。然而,两个 observable 的结果完全不同(一个是 formGroup,一个是字符串),它们都需要以不同的方式处理。
// Get latest value of all observables
merge(
this.parentFormGroup.controls['ProductOwner'].valueChanges,
// Get current value of Record Form
this.recordFormService.recordForm$
)
【问题讨论】:
标签: angular observable rxjs6