What's wrong with my $ firebase $ promise in the service?

I am learning AngularJS and Firebase and am using AngularFire 0.8.2 (Old I know). I want the (getAccount) function to return an array identical to initAccount from firebase. The firebase url works, but I don't know how to get the function to return an array. Any help would be appreciated :)

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;
};

      

});

+3


source to share


1 answer


You can use a service $q

to have your function return a promise. Here's your code with this

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;
    };
});

      



To use it, just call your function and then process the data using the method 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); 
    });
});

      

+4


source







All Articles