Angular 5 RxJS 订阅计时问题

标签 angular typescript rxjs observable

对 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/

相关文章:

javascript - RxJS 扫描并结合最新行为

html - 为什么 ng-hide 和 ng-show 不起作用?

javascript - 使用 webpack 的 ng2-translate 中未加载 JSON 文件

angular - "Circular dependency detected"警告 - Angular

typescript - 如何在 Angular 2/Typescript 中声明一个全局变量?

javascript - Angular RxJs - 在第二个流中填充数组(嵌套流)

javascript - 如何确保 Observable.map 仅在成功时执行?

typescript - Typescript 中的多种类型谓词

javascript - 模块/类的 TypeScript/导入和导出 - 运行导入类时出现运行时错误

javascript - 获取特定索引处的可观察数组元素 [html]