【问题标题】:What's wrong with my $firebase $loaded promise in a service?我在服务中的 $firebase $loaded 承诺有什么问题?
【发布时间】:2015-04-20 09:53:40
【问题描述】:

我正在学习 AngularJS 和 Firebase 并使用 AngularFire 0.8.2(我知道旧版本)。 我想要一个函数(getAccount)从firebase返回一个与initAccount相同的数组。 firebase URL 有效,但我不知道如何使函数返回数组。任何帮助将不胜感激:)

app.service('DataService', function(FURL, $firebase) {

var ref = new Firebase(FURL);

//initial account array to load
this.account = [
  {'info':'Sig1'},
  {'info':'Sig2'},
  {'info':'Sig3'}
];

this.getAccount = function(user) {
    var uid = user.uid;
    var dir = 'profile/' + uid + '/account';

    var accountSigs = $firebase(ref.child(dir)).$asArray().$loaded().then(function(response) {

      //show response returns [[object Object],[object Object],[object Object]] with correct data as it should.
      console.log('show response: [' + response + ']');

      return response;
    });

    // this returns [[object Object]] but I don't know why
    console.log('show accountSigs: [' + accountSigs + ']');

    return accountSigs;
};

});

【问题讨论】:

    标签: angularjs firebase loaded


    【解决方案1】:

    您可以使用$q 服务让您的函数返回一个承诺。 这是你的代码

    app.service('DataService', function (FURL, $firebase, $q) {
    
        var ref = new Firebase(FURL);
    
        //initial account array to load
        this.account = [
            {'info': 'Sig1'},
            {'info': 'Sig2'},
            {'info': 'Sig3'}
        ];
    
        this.getAccount = function (user) {
            var uid = user.uid;
            var dir = 'profile/' + uid + '/account';
            var defered = $q.defer();
    
            var accountSigs = $firebase(ref.child(dir)).$asArray().$loaded().then(function (response) {
                console.log('show response: [' + response + ']');
                defered.resolve(response);
            });
    
            return defered.promise;
        };
    });
    

    要使用它,只需调用您的函数,然后使用then() 方法操作数据。

    app.controller('MyController', function(DataService) {
        DataService.getAccount().then(function (data) {
    
            //Data will contain what is passed as parameter to defered.resolve()
            console.log(data); 
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2019-06-20
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多