我需要一些Angular和Promises的帮助,因为我在这里做错了:
var rootModule = angular.module('ims2Root',[]);
rootModule.controller('RootController', ['$q', '$scope', '$http', '$state', 'user', function ($q, $scope, $http, $state, user) {
$scope.title = "IMS2";
user.getUserList().then(function (data) {
console.log('loaded' , data.data);
console.log('fuuu', user.getUserName(1));
});
console.log('fooo', user.getUserName(1));
}]);
rootModule.factory('user', ['$q','$http', function ($q, $http) {
var services = {};
services.getUserList = function () {
return $http.get('/api/acc/getlist');
}
services.getUserName = function (id) {
this.getUserList().then(function (data) {
angular.forEach(data.data, function (val, key) {
if (data.data[key].id == id) {
console.log('found',val, data.data[key].userName);
return data.data[key].userName;
}
})
return 'not found:' + id;
});
}
return services;
}]);
输出:
fooo undefined
loaded [Object { id=2, userName="icn36101"}, Object { id=3, userName="icn36115"}, Object { id=1, userName="icn36121"}]
fuuu undefined
found Object { id=1, userName="icn36121"} icn36121
found Object { id=1, userName="icn36121"} icn36121`
所以我的问题是getUserName()console.log如何从正确的对象获取字符串,但它的函数确实返回undefined。
在getUserName()中,返回就在记录正确找到的值的行之后,那么为什么控制台登录函数会在返回下一行之后被调用?
答案 0 :(得分:0)
您需要从getUserName
方法
services.getUserName = function (id) {
return this.getUserList().then(function (data) {
angular.forEach(data.data, function (val, key) {
if (data.data[key].id == id) {
console.log('found',val, data.data[key].userName);
return data.data[key].userName;
}
});
return 'not found:' + id;
});
}