【问题标题】:Stuck: AngularJs using factory with http call to json卡住:AngularJs 使用带有 http 调用 json 的工厂
【发布时间】:2016-02-18 11:10:15
【问题描述】:

我很震惊,无法理解这里的问题。 我使用对我的 json 文件的 http 服务调用创建了一个工厂 工厂(accountInfo.json):

appRoot.factory('accountInfo', ['$http', function($http) { 
  return $http.get('../../accountInfo.json') 
    .success(function(data) { 
      return data; 
    }) 
    .error(function(err) { 
      return err; 
    }); 
}]);

控制器(AccountsController.js)

appRoot.controller('AccountsController', ['$scope', 'accountInfo', function($scope, accountInfo){

    accountInfo.success(function(data) {
      $scope.rows = data;
    });


    $scope.totals = {
        name: '',
        marketValue: 0,
        cash: 0,
        legend: 'none'
    };

    for (var i = 0; i < $scope.rows.length; i++) {
        $scope.totals.marketValue += $scope.rows[i].marketValue;
        $scope.totals.cash += $scope.rows[i].cash;
    }


    $scope.addAccount = function() {
        $scope.rows.push({
            name: 'New Account',
            marketValue: Math.random() * 100000,
            cash: Math.random() * 400000,
            legend: 'cyan'
        });
    }
}]);

我的 json (accountInfo.json)

[{
    "name": "Brokerage Account 3",
    "marketValue": 1999990,
    "cash": 1995826,
    "legend": "orange"
},
{
    "name": "Account 3",
    "marketValue": 1949990,
    "cash": 1695856,
    "legend": "darkorange"
},
{
    "name": "Brokerage Account 1",
    "marketValue": 1349990,
    "cash": 1595866,
    "legend": "red"
},
{
    "name": "Brokerage Account 4",
    "marketValue": 155990,
    "cash": 160826,
    "legend": "blue"
},
{
    "name": "Brokerage Account 2",
    "marketValue": 74560,
    "cash": 19956,
    "legend": "gray"
},
{
    "name": "Account 4",
    "marketValue": 55006,
    "cash": 53006,
    "legend": "salmon"
},
{
    "name": "Account 13",
    "marketValue": 37340,
    "cash": 0,
    "legend": "green"
},
{
    "name": "Joint Account 1",
    "marketValue": 28308,
    "cash": 4167,
    "legend": "darkblue"
},
{
    "name": "Joint Account 2",
    "marketValue": 10000,
    "cash": 10000,
    "legend": "teal"
}]

我收到的错误是“$scope.rows 未定义” 控制器无法在成功函数之外访问 $scope.rows。

谢谢:)

【问题讨论】:

  • 那么,有什么问题?

标签: angularjs service factory


【解决方案1】:

你需要在你的控制器中解决promise,而不是在你的工厂中,只需返回promise:

appRoot.factory('account', ['$http', function($http) { 
    return {
        info: function () {
            return $http.get('../../accountInfo.json');
        }
    }
}]);

然后在你的控制器中做:

appRoot.controller('AccountsController', ['$scope', 'account', function($scope, account){

    account.info()
        .success(function(data) { 
            $scope.rows = data;
        }) 
       .error(function(err) { 
            return err; 
        }); 

}]);

仅供参考,successerror 方法已弃用:

不推荐使用 $http 旧式承诺方法成功和错误。请改用标准 then 方法。如果 $httpProvider.useLegacyPromiseExtensions 设置为 false,那么这些方法将抛出 $http/legacy 错误。

见:https://docs.angularjs.org/api/ng/service/$http

使用then 方法:

account.info().then(
    function resolved (response) {
        $scope.rows = response.data;
    },
    function rejected (response) {
        alert(response.status + ': ' + response.statusText);
    }
);

这是该概念的一个工作示例:http://plnkr.co/edit/UtJDpvBKKYl4rBzgXYo4?p=preview

【讨论】:

  • 谢谢,我做了同样的事情,但仍然面临这个问题。我收到的错误是“$scope.rows 未定义”控制器无法在成功函数之外访问 $scope.rows。 .在控制器内部,我能够访问数据对象的成功函数。
  • 我已经改变了被拒绝的方法来抛出一个警报,如果请求被拒绝,你应该看到它,并在我的答案中添加了一个关于 Plunker 的工作示例。希望对您有所帮助。
  • 非常感谢!我在这里很新,并试图了解正在发生的事情。我还在我的控制器中添加了一个刷新功能,并且能够在 HTML 视图中访问我的数据以及刷新它。但是我无法在控制器内部的函数之后访问 $scope.rows 。因此无法访问长度属性。 Plunker 路径:plnkr.co/edit/aB6ZJB5QXn5jqULfGTga?p=preview 文件 accountController.js 行号。 24. 我确信这与我遗漏的一些核心逻辑有关。
【解决方案2】:

当你这样调用它时,你应该返回一个获取数据的函数:

appRoot.factory('accountInfo', ['$http', function($http) { 
    return {
        fetchData: fetchData
    };

    function fetchData() {
        return $http.get('../../accountInfo.json');
    }
}]);

然后在你的控制器中你可以这样做:

accountInfo.fetchData()
    .then(
        function(data) {
            console.log(data);
        },
        function(error) {
            console.log(error);
        }
    );

【讨论】:

  • 谢谢,我做了同样的事情,但仍然面临这个问题。我收到的错误是“$scope.rows 未定义”控制器无法在成功函数之外访问 $scope.rows。在控制器内部,我可以访问数据对象的成功函数。
【解决方案3】:

感谢大家的帮助。 我通过引导应用程序解决了我的问题。由于 http 调用未完成,我最初无法访问我的数据。

angular.element(document).ready(function() {
    angular.bootstrap(angular.element(document), ['app']);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多