【问题标题】:How to properly convert Observable into Array [duplicate]如何正确地将 Observable 转换为 Array [重复]
【发布时间】:2021-05-02 19:10:16
【问题描述】:

我目前正在尝试将 Observable 转换为数组,以便我可以使用 ngFor 遍历 HTML 中的数组。

这是我目前的 Typescript 代码。当我控制台记录 testArray 数组时,它说它是未定义的。

item$: Observable<any[]>;
testArray: Array<any[]>;

  constructor(
    private afs: AngularFirestore,
    private route: ActivatedRoute,
  ) {
      this.item$ = afs.collection('testsTaken', ref => ref.where('testCreator', '==', this.id).where('testTitle', '==', this.testTitle)).valueChanges();
      this.item$.subscribe(x => this.testArray = x);
      console.log(this.testArray); // yields undefined
 
  }

I tried the advice given for this post and I still cant get it to work

【问题讨论】:

    标签: javascript arrays angular rxjs observable


    【解决方案1】:

    console.log() 打印未定义,因为您的订阅在 console.log 打印后发出,因此数组仍然未定义。 您可以检查它并进行如下更改:

     this.item$.subscribe(x => {
       this.testArray = x;
       console.log(this.testArray);
     });
    

    如果你想使用数组在 *ngFor 上运行,你有 2 个选项:

    选项 1:

    this.item$.subscribe(x => this.testArray = x);
    

    您可以在模板中使用它,例如(示例):

    <div class="test" *ngFor="let item of testArray"> {{item}} </div>
    

    选项 2:

    异步管道(您可以在此处阅读更多信息:https://angular.io/api/common/AsyncPipe) 简而言之,这与在组件类型脚本中订阅但在模板中订阅相同(使用它有很多好处)。

    示例代码:

    <div class="test" *ngFor="let item of item$ | async">{{item}} </div>;
    

    【讨论】:

      【解决方案2】:

      Observable 异步工作。 Javascript 不会在订阅之外等待它的结果,并且您的 console.log() 早在处理 Observable 内的代码之前就已被触发。看看这个:

      this.item$.subscribe(x => {
             this.testArray = x;
             console.log(this.testArray);
      });
      

      【讨论】:

        猜你喜欢
        • 2014-10-24
        • 2019-05-17
        • 1970-01-01
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 2018-01-27
        • 2018-03-19
        • 2017-06-02
        相关资源
        最近更新 更多