【问题标题】:Angular 5 RxJS Subscription Timing IssueAngular 5 RxJS 订阅时间问题
【发布时间】:2018-07-19 12:48:13
【问题描述】:

Angular RxJS observables 新手,在时间和如何处理以下场景方面遇到问题。

我正在使用 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 可用。

【问题讨论】:

  • 如果 getRecType 是异步的,isRecord 也需要是异步的,并且应该返回一个 observable。

标签: angular typescript rxjs observable


【解决方案1】:

您可以通过以下方式实现:

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,它会返回你的真假。现在在isRecord 中,您还可以映射返回值并在您想要的任何函数中使用它。最后,您在放置所有组合后订阅。通过这种方式,你告诉 Rxjs 如何处理流。

这只是一种简单的可能方式。我敢打赌还有很多其他方法。

使用 Rxjs6 非常相似。而不是.map(,而是.pipe(map(pipe 是一个可出租的运算符,它有助于更​​轻松地链接运算符。同样使用它们可以减少应用程序的最终包大小。

【讨论】:

  • @msanford,谢谢,我会补充。我不使用 lettable 运算符,因为我不知道 OP 使用哪个版本,但也会添加它
  • 是的,它确实保持与 OP 相同的语法!这只是给社区中其他读者的一个注释,不一定是你的回答“错误”:)
  • 使用 rxjs: 5.5.2 和 angular 5.2.1
  • @tonyf,所以我的帖子是您应该使用的语法。注意 - 你仍然可以使用 Rxjs6 包,只需要添加一个依赖项rxjs-compat。我会建议这种方法,因为捆绑包的大小会减小
  • @yourFather 使用你的地图语法,因为我不熟悉这个,我需要导入任何 rxjs 运算符吗?谢谢。
【解决方案2】:

您不能像那样从异步转到同步。如果您使用的是异步方法,那么使用它的方法也必须是异步的。

所以,像这样(代码未验证):

  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 这两个流。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2021-11-18
    相关资源
    最近更新 更多