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
的值似乎无法及时返回以满足我的整个布尔返回值
如何在Angular 5中解决这个问题?我需要确保为上述处理返回一个布尔值,并且在isRecord返回其结果时this.type
可用。
答案 0 :(得分:2)
您可以通过以下方式实现这一目标:
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();
}
不是通过map
中的结果来订阅getRecType
,而是返回true或false。现在,在isRecord
中,您还可以映射返回值并将其用于所需的任何函数中。最终,在所有组合放置之后,您进行订阅。这样,您就可以告诉Rxjs如何处理流。
那只是一种简单的可能方式。我敢打赌,还有很多其他方法。
使用Rxjs6非常相似。您可以执行.map(
而不是.pipe(map(
。 pipe
是可出租的运算符,它有助于更轻松地链接运算符。此外,使用它们还可以减小应用程序的最终捆绑包大小。
答案 1 :(得分:1)
您不能只从异步转到像这样同步。如果您使用的是异步方法,则使用它的方法也必须是异步的。
所以,类似这样的代码(未经验证的代码):
public getRecType(myRec: string): Observable<boolean> {
return this.myService.getRecType(myrec).map(recType => !!recType);
}
public isRecord(rc: any): Observable<boolean> {
return this.getRecType().map(recType => {
_.find(this.record, { name: rc }) && this.type
});
}
编辑:仅在_.find()
为同步时有效。如果没有,您将不得不再次使用Observables并可能combineLatest
这两个流。