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

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

问题描述

我尝试了解.valueChanges()和.subscribe() 我使用 AngularFire2 Angular5

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()时,它将返回一个可观察值.什么是可观察的?

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

可观察对象打开了一个连续的沟通渠道,其中随着时间的推移可以发出多个数据值.

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

因此,要从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()函数发生了什么? (angularfire2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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