Sem Horse
Sem Horse

Reputation: 43

How to pass data from factory to controller?

Here is my code for sending an object from server to factory:

app.post('/userdata',function(req,res){
    connection.query('select * from users',(err,rows)=>{
        sess = req.session;
        for(var i = 0;i < rows.length; i++){
              var user = rows[i];
            if(sess.emails == user.user_email){
                    sess.username = user.user_name,
                    sess.usersurname = user.user_surname,
                    sess.userid = user.user_id,
                    sess.userphoto = user.user_photo,
                    sess.balance = user.user_balance,
                    sess.currency = user.user_balance_currency

                    var UserData = {
                        id: sess.userid,
                        username: sess.username,
                        usersurname: sess.usersurname,
                        emails: sess.emails,
                        userphoto: sess.userphoto,
                        balance: sess.balance,
                        currency: sess.currency
                    }

                     res.json(UserData);
            };

        };

    })
});

Here is my code for receiving the object from server in factory:

angular.module('CoinKeeperApp').factory("CoinKeeperAPI", function ($http) {
    return {

             getUserData: function () {

            $http.post('/userdata').then(function(response){


                var result = response.data.balance
                console.log(result);
                    return result;
            })
        }
    }
});

Here is my code for the controller. I can`t get an access to the object received from the factory.

angular.module('Navigation', [])

.controller("navCtrl", function (CoinKeeperAPI) {
    this.CoinKeeperAPI = CoinKeeperAPI;
       this.CoinKeeperAPI.getUserData();
      **this.balance = this.result;**


});

How I can get access to the object in the Controller?

Upvotes: 0

Views: 411

Answers (1)

G07cha
G07cha

Reputation: 4154

To receive data from promise you need to return it in the factory's function

In factory:

angular.module('CoinKeeperApp').factory("CoinKeeperAPI", function ($http) {
    return {
        getUserData: function () {
            return $http.post('/userdata').then(function(response){
                var result = response.data.balance

                return result;
            })
        }
    }
});

In controller:

angular.module('Navigation', [])
.controller("navCtrl", function (CoinKeeperAPI) {
    var vm = this;
    this.CoinKeeperAPI = CoinKeeperAPI;
    this.CoinKeeperAPI.getUserData().then(function(result) {
        vm.balance = result;
    });
});

Note: Promises are asynchronous, all received data will be available only after then chain call will be invoked.

Upvotes: 1

Related Questions