Angular-$http范围问题

Angular - $http Scope Issue

本文关键字:问题 范围 http Angular-      更新时间:2024-05-20

我目前正在使用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问题/答案,这一个似乎是最相关的。

我想这就是您想要的答案。您应该将.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];
  });
}]);