[英]JavaScript rxjs filter not working when returning an Observable
我正在使用 Angular 9. 我正在尝试过滤 Observable 中的值,但它没有影响。 我认为我处理 Observable 的方式是错误的。
下面, _filter
function 应该过滤this.filteredApproverOptions
,但是我发现没有应用过滤器并且总是填充整个列表。
private setFilteredApproverOptions(): void {
for (const field in this.approvalEditFormGroup.controls) {
this.approvalEditFormGroup.get(field).valueChanges.subscribe(value => {
if (value && typeof value.valueOf() === "string") {
this.filteredApproverOptions = this._filter(value);
const x = parseInt(field.charAt(9));
const y = parseInt(field.charAt(12));
this.filteredApproverOptions = this.filteredApproverOptions.pipe(map( // obs.pipe(map(...)) is changing each value coming in an observable/subject
pArr => pArr.map(p => ({...p, x: x, y: y})) // arr.map(...) is changing each value in an array
));
}
});
}
}
private _filter(value: string): Observable<Person[]> {
const filterValue: string = value.toLowerCase();
let respApprovalState: Observable<Person[]> = this.getApproverOptions(filterValue);
respApprovalState.subscribe(approverOptions => {
return approverOptions.filter((option: Person) => {
let filter: boolean =
(option.firstName.toLowerCase().includes(filterValue) || option.lastName.toLowerCase().includes(filterValue))
return filter; // if this returns true or false, there is no difference
});
});
return respApprovalState;
}
题
如何将过滤器应用于this.filteredApproverOptions
?
您不需要在订阅中运行副作用,而是需要返回新的可观察对象并在将来使用它。 与上面的map
相同,例如:
return respApprovalState.pipe(
filter(option => ...)
)
要正确使用 Observable,您不应该订阅它,直到您使用数据(最后)。
你必须 pipe 你的 Observable 并在其中添加你的过滤器:
return respApprovalState.pipe(
filter(data => ...) // Filter the data running through your pipe
);
不幸的是,您没有提供足够的信息来了解什么是approverOptions
,我们将无法为您提供一个工作示例。
但是在理解了 Rxjs Observables 的模式后,你应该可以自己做。
以下是有关过滤器运算符的更多信息: https://rxmarbles.com/#filter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.