angular - 循环遍历 Typescript 中的 observable<Object[ ]>

标签 angular typescript rxjs observable

我有一个 firebase 数据库...所以它都是 JSON。 我使用 AngularFire2 数据库检索数据...我正在阅读 this教程...

这道题的部分代码是:

noteList: Observable<Note[]>

  constructor(public navCtrl: NavController, private noteListService: NoteListService) {
    this.noteList = this.noteListService.getNoteList()
      .snapshotChanges()
      .map(
      changes => {
        return changes.map(c => ({
          key: c.payload.key, ...c.payload.val()
        }))
      });

从这里我想做两件事:

  • 1st : 在构造函数之外声明一个数组变量,就像 noteList Ex : myVar: Note[] = new Array();
  • 第二:可迭代 getNoteList() 的结果并将它们插入该变量以供进一步使用...我希望 myVar 持有 的多个对象code>Note ...=> 这些是来自 Firebase 的 JSON,因此是 JavaScript 对象...

我该怎么做?

到目前为止,我使用的是以下内容:

this.noteList .forEach(value => console.log(value)); 这会将 noteList 的每个元素记录为 Array [Object] ....

当我执行 this.noteList .forEach(value => this.myVar.push(value)); 时,它说:

Argument of type 'Note[]' is assignable to parameter of type 'Note'. Property 'id' is missing in type 'Note[]'

完整的类代码是:

export class HomePage {

  noteList: Observable<Note[]>
  myVar : Note[] = new Array();

  constructor(public navCtrl: NavController, private noteListService: NoteListService) {
    this.noteList = this.noteListService.getNoteList()
      .snapshotChanges()
      .map(
      changes => {
        return changes.map(c => ({
          key: c.payload.key, ...c.payload.val()
        }))
      });
  }

  this.noteList .forEach(value => this.myVar.push(value));

  //Then below, I want to use it in a Jquery 

  $(function() {
     // Also, I don't know how to access neither noteList nor myVar here. Any help here will be appreciated also
  }
}

请你们帮忙做这件事...

最佳答案

使用 RxJS 执行此操作的正确方法是订阅一个可观察对象,并在 subscribe 回调中执行所有必要的操作并返回结果。如果不重用可观察对象,则无需将其保存到 noteList,但可能需要保存订阅以便取消订阅并避免内存泄漏:

  noteListSubscription: Subscription;

  constructor(private noteListService: NoteListService) {
    this.noteListSubscription = this.noteListService.getNoteList()
      .snapshotChanges()
      .map(
      changes => {
        return changes.map(c => ({
          key: c.payload.key, ...c.payload.val()
        }))
      })
      .subscribe(notes => { this.myVar = notes });
  }

  ngOnDestroy() {
    noteListSubscription.unsubscribe();
  }

订阅类型应该从rxjs模块导入。

关于angular - 循环遍历 Typescript 中的 observable<Object[ ]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089583/

相关文章:

angular - Angular 中多个相同的异步管道导致多个 http 请求

javascript - 将数据推送到另一个对象

angular - 静态服务器端渲染或动态服务器端渲染

Angular 8 - 在前端更改检测问题上调整图像大小

带有索引器的 typescript 递归类型

angular - 类型 'first' 上不存在属性 'Observable<string>'

rxjs - 使用相应的 flatMap 结果压缩值

javascript - 如何通过 rxjs 运算符操作从请求中获取的对象?

Angular:删除 [ngValue] 绑定(bind)字符串的最后 4 个字符

javascript - 产品中的 Angular 4 SEO 友好解决方案