简体   繁体   English

从$ rootScope存储和访问快照值

[英]Storing and Accessing snapshot value from $rootScope

In my global controller (assigned to the body in html) I have the following code to grab a snapshot of firebase one time. 在我的全局控制器中(用html分配给主体),我有以下代码可以一次捕获firebase的快照。

ref.once('value', function(snapshot){
    var data = snapshot;
}).then(function(data){
    $rootScope.content = data.val();
});

I am using the content in my HTML templates to render them. 我正在使用HTML模板中的内容来呈现它们。 All the questions I found had resulted in putting the "then" code inside the callback. 我发现的所有问题都导致将“ then”代码放入回调中。

Literally all I need to do is be able to grab a snapshot one time and store it on $rootScope.content and access it outside of the function, ie anywhere in my app. 从字面上看,我需要做的就是能够捕获一次快照并将其存储在$rootScope.content并在函数外部(即我的应用程序中的任何位置)进行访问。

I'm pretty sure it's because everything is rendering prior to firebase returning anything, I'm just not sure the best way to tell it to wait. 我很确定这是因为所有内容都是在Firebase返回任何内容之前渲染的,我只是不确定告诉它等待的最佳方法。

Thank you in advance. 先感谢您。

Try: 尝试:

ref.once('value', function(snapshot){
    $rootScope.content = snapshot.val();
});

Or: 要么:

ref.once('value').then(function(snapshot){
    $rootScope.content = snapshot.val();
});

From the once() docs: once()文档:

Return Value Returns a Promise that can optionally be used instead of the successCallback and failureCallback to handle success and failure. 返回值返回一个Promise,可以选择使用Promise代替successCallback和failureCallback来处理成功和失败。

I think your second line var data = snapshot; 我认为您的第二行var data = snapshot; may be the problem? 可能是问题吗? If all you want is to get the whole database and assign it to a object called $rootScope.content , or anything else, the below would work. 如果您只想获取整个数据库并将其分配给名为$rootScope.content或其他任何对象的对象,则可以使用以下内容。 I don't use angular but $rootScope.content would need to be an object, aka var foo = {} would be able to take snapshot.val() . 我不使用angular,但是$rootScope.content需要成为一个对象,又名var foo = {}将能够使用snapshot.val() Note that snapshot.val() is full of stuff other than just your JSON formatted data and you will have to extract out your individual nodes by calling the property names (the key's), eg snap.val().firstName to get Bob . 请注意, snapshot.val()不仅包含您的JSON格式数据,而且还包含其他东西,您将必须通过调用属性名称(键的名称)(例如snap.val().firstName来提取单个节点,以获取Bob

firebase.database().ref('/').once('value').then(function(snap) {
  $rootScope.content = snap.val();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM