对 Angular RxJS 可观察量不熟悉,我在时间安排以及如何处理以下场景方面遇到了问题。
我正在使用 RxJS:5.5.2 和 Angular 5.2.1
我有以下代码:
public checkRecType(myrec: string) {
this.myService.getRecType(myrec).subscribe(
result => {
if (result) {
this.recType = true;
} else {
this.recType = false;
}
});
}
public isRecord = (rc: any): boolean => {
this.checkRecType(rc);
return (_.find(this.record, {'name': rc}) && this.type);
}
我遇到的问题是,当我检查调用 checkRecType 的 isRecord
时,上面订阅中的 this.type
值似乎没有返回及时满足我的整个 bool 返回。
如何在 Angular 5 中解决这个问题?我需要确保为上述处理返回一个 bool 值,并且当 isRecord 返回其结果时 this.type
可用。
最佳答案
您可以通过以下方式实现这一目标:
import "rxjs/add/operator/map"
import { Observable } from "rxjs/Observable"
public checkRecType(myrec: string): Observable<any> {
return this.myService.getRecType(myrec).map(
result => {
if (result) {
this.recType = true;
} else {
this.recType = false;
}
return this.recType;
// or instead you could (_.find(this.record, {'name': rc}) && this.recType);
});
}
public isRecord = (rc: any) => {
this.checkRecType(rc).map(res =>
(_.find(this.record, {'name': rc}) && res);
).subscribe();
}
而不是通过 getRecType
中的结果订阅您map
,它会返回 true 或 false。现在,在 isRecord 中,您还可以映射返回值并在您想要的任何函数中使用它。最后,您在放置所有组合后进行订阅。通过这种方式,你告诉 Rxjs 如何处理流。
这只是一种简单的可能方法。我敢打赌还有很多其他方法。
使用 Rxjs6 非常相似。而不是 .map(
你做 .pipe(map(
)。 pipe
是一个可出租运算符,它有助于更轻松地链接运算符。也使用它们您可以减少应用程序的最终包大小。
关于Angular 5 RxJS 订阅计时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51423119/