1

I have created the service below.

    app.factory('userProfileFactory', ['FBDB', 'searchParam', function(FBDB, searchParam) {
            var personalKey;
        return {

            userProfile: function() {
                var FBref = new Firebase(FBDB).child('items');
                FBref.orderByChild('first')
                    .startAt(searchParam)
                    .endAt(searchParam)
                    .once('value', function (snapshot) {
                    var data = snapshot.val();

                        personalKey = Object.keys(data)[0];

                        return(personalKey);     
                });

                return(personalKey);

            }
        };
    }]);

However, when I try to get the results of the value of personalKey in the controller below, I get "undefined":

app.controller('profileCtrl', ['userProfileFactory', function(userProfileFactory) {

console.log(userProfileFactory.userProfile())

}]);

Please advice :)

1 Answer 1

3

Yes, you could Create a custom promise at that place where you are trying to expecting to get data in asynchrous manner by taking help from $q

userProfile: function() {
  var deferred = $q.defer();
  var FBref = new Firebase(FBDB).child('items');
  var promise = FBref.orderByChild('first')
  .startAt(searchParam)
  .endAt(searchParam)
  .on('value', function(snapshot) {
    var data = snapshot.val();
    personalKey = Object.keys(data)[0];
    deferred.resolve(personalKey);
  });
  return deferred.promise
}

And then controller will call the factory function with .then function to chain promise.

app.controller('profileCtrl', ['userProfileFactory', function(userProfileFactory) {
    userProfileFactory.userProfile().then(function(res){
      console.log(res);
    })
}]);
Sign up to request clarification or add additional context in comments.

4 Comments

Works Perfectly. Very grateful :)
@JohnCarson Glad to help you. Thanks :-)
@PankajParkar Thank you. I was looking for the same.
@MunamYousuf Glad to know that I helped you as well, Cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.