Angular5 valuechanges() 函数发生了什么?(角火2) [英] Angular5 what's happened with valuechanges() function ? (angularfire2)

查看:21
本文介绍了Angular5 valuechanges() 函数发生了什么?(角火2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to understand .valueChanges() and .subscribe() I use AngularFire2 and Angular5

我的代码有效,但我不明白它是如何工作的.

My code works but I don't understand how it works.

我的组件:

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

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

console.log give a beautiful array : 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?

console.log give Object { _isScalar: false, source: {…}, operator: {…} } euh WTF ?

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

QUESTION: what's happened in the service to give this strange object and how I am able to recover a beautiful array in my component ? Thank you

推荐答案

因此,当您在 AFS 中执行 .valueChanges() 时,它将返回一个 observable.什么是 Observable?

So when you do .valueChanges() in AFS then it is going to return an observable. What is an Observable?

Observable 开辟了一个连续的通信渠道,随着时间的推移,可以发出多个数据值.

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

因此要从 Observable 中获取值,您必须订阅它.因此,在您的组件中,您订阅了它,因此它会在值发生变化时记录实际数组.在您的服务中,您实际上只是在记录一个看起来很奇怪的 observable,并且没有像您期望的那样记录.如果你想让你的服务记录一个数组,你可以这样做:

So to get a value from an Observable you must subscribe to it. So in your component you are subscribing to it so it will log the actual array anytime the value changes. In your service you are literally just logging an observable which looks really weird and does not log like you would expect. If you wanted your service to log an array you could do this:

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

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

Hope that helps, let me know if you need any further clarification.

这篇关于Angular5 valuechanges() 函数发生了什么?(角火2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆