以下是我将代码从服务器发送到工厂的代码:
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);
};
};
})
});
这是我在工厂从服务器接收对象的代码:
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;
})
}
}
});
这是我的控制器代码。我无法访问从工厂收到的对象。
angular.module('Navigation', [])
.controller("navCtrl", function (CoinKeeperAPI) {
this.CoinKeeperAPI = CoinKeeperAPI;
this.CoinKeeperAPI.getUserData();
**this.balance = this.result;**
});
如何访问Controller中的对象?
答案 0 :(得分:1)
要接收来自承诺的数据,您需要在工厂的功能中返回
在工厂:
angular.module('CoinKeeperApp').factory("CoinKeeperAPI", function ($http) {
return {
getUserData: function () {
return $http.post('/userdata').then(function(response){
var result = response.data.balance
return result;
})
}
}
});
在控制器中:
angular.module('Navigation', [])
.controller("navCtrl", function (CoinKeeperAPI) {
var vm = this;
this.CoinKeeperAPI = CoinKeeperAPI;
this.CoinKeeperAPI.getUserData().then(function(result) {
vm.balance = result;
});
});
注意:Promise是异步的,所有收到的数据只有在调用then
链调用后才可用。