我目前正在使用Angular,并且$http
有问题。我的几个控制器仅使用$http
文件,将结果应用于$scope.variable
,但是在我当前的控制器上,我遇到了问题。
app.factory('getUserData', function($http) {
var user = [],
url = 'res/asp/manageaccount.asp?action=',
custid = getCookie('custid');
return {
getUserInfo: function() {
url += 'getUserInfo&custid=' + custid;
return $http.get(url);
},
getShipInfo: function(callback) {
url += 'getShipInfo&custid=' + custid;
return $http.get(url).then(function(response) {
user = response.data;
return user;
});
}
};
});
app.controller('accountController', ['$scope', 'getUserData',
function($scope, getUserData) {
$scope.custid = getCookie('custid');
getUserData.getUserInfo().then(function(data) {
$scope.userInfo = data.data;
console.log($scope.userInfo); // Logs the array with the object data I need
});
// Accessing $scope.userInfo here is 'undefined'
}
]);
我尝试了两种不同的方法来返回数据。数据返回正常,但是我无法在页面中访问它-仅在定义
$scope.userInfo
的范围内。获取数据并不是它显示在页面上的问题。<div class="container" ng-controller="accountController">
<h1>Welcome Back, {{userInfo.fname}}!</h1> <!-- Doesn't work -->
<div class="row" ng-controller="cartController">
<!-- This works fine -->
</div>
<div class="row">
{{userInfo.fname}} <!-- Doesn't work -->
{{custID}} <!-- Works -->
</div>
</div>
TL; DR
$http
返回数据,但无法使用页面中的{{userInfo.fname}}
进行访问。我看过很多SO问题/答案,而这似乎是最多的relevant。
最佳答案
我认为这是您正在寻找的答案。您应该将.then(data)
重命名为.then(response)
以避免混淆。 response.data[0]
应该是对象
app.controller('accountController', ['$scope', 'getUserData', function($scope, getUserData)
{
$scope.custid = getCookie('custid');
getUserData.getUserInfo().then(function(response)
{
$scope.userInfo = response.data[0];
});
}]);