observable - Angular5 valuechanges() 函数发生了什么? (角火2)

标签 observable angularfire2 angular5 subscribe

我试着理解 .valueChanges() 和 .subscribe() 我使用 AngularFire2Angular5

我的代码可以工作,但我不明白它是如何工作的。

我的组件:

ngOnInit() {
    this.itemService.getLastUnicorns().subscribe(items => {
        this.items = items;
        console.log(items);
    });
}

console.log 给出一个漂亮的数组:Array [ {…}, {…} ]

我的服务:

getLastUnicorns() {
    this.items = this.afs.collection('unicorns', ref => ref.limit(2)).valueChanges();
    console.log(this.items);
    return this.items;
}

console.log 给出 Object { _isScalar: false, source: {...}, operator: {...} } 呃 WTF?

问题:在提供这个奇怪对象的服务中发生了什么,我如何能够在我的组件中恢复一个漂亮的数组? 谢谢

最佳答案

因此,当您在 AFS 中执行 .valueChanges() 时,它将返回一个可观察对象。什么是 Observable?

Observables open up a continuous channel of communication in which multiple values of data can be emitted over time.

因此,要从 Observable 中获取值,您必须订阅它。因此,在您的组件中,您正在订阅它,因此它会在值更改时随时记录实际数组。在您的服务中,您实际上只是在记录一个看起来很奇怪并且不像您期望的那样记录的可观察对象。如果您希望您的服务记录一个数组,您可以这样做:

this.items = this.afs.collection('unicorns', ref => ref.limit(2))
     .valueChanges()
     .subscribe(data=>{
         console.log(data);
        })

希望对您有所帮助,如果您需要进一步说明,请告诉我。

关于observable - Angular5 valuechanges() 函数发生了什么? (角火2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48436482/

相关文章:

Angular 4.3 可观察量 : how to retry with an interval and max retries?

json - Angular 4 - 错误类型错误,错误上下文 DebugContext_

angular - 使用 angularfire 过滤来自 Firestore 的数据

angular5 - 如何从 angular 5 的 url 下载 pdf 文件

angular - 更新绑定(bind)对象的内容时不会触发 onChanges

angular - 按对象属性过滤可观察数组

angular - 使用 catchError 更新组件

javascript - Firebase 查询子级的子级是否包含值

firebase - 在 AngularFireAuth 中获取当前用户

javascript - 如何在angular 5中以编程方式转换html元素