javascript - angularjs 类型错误 : undefined is not a function factory

标签 javascript json angularjs angularjs-service angularjs-http

我正在玩 angularjs。我正在尝试简单地从 json 文件中提取数据。当我运行代码时,文件显示在网络中,但数据未显示在页面上,并且我在控制台中收到以下错误:

TypeError: undefined is not a function at Ob (lib/angular-1-2/angular.min.js:14:6)

我使用的代码如下:

var Services = angular.module('Services', ['ngResource']);
Services.factory('reportFactory', function($http){
    console.log(REPORT_LIST_URL);
    return{
        getReports: function(callback){
            $http.get(REPORT_LIST_URL).success(callback);
        }
    }
});

function ReportsCtrl($scope, $http, reportFactory) {
    $scope.reportsList = [];
    console.log($scope.reportsList);
    console.log("Get report list from json file");
    console.log("before the factory");
    reportFactory.getReports(function(data){
       $scope.reportsList = data;
    });
}

json 文件示例

{
  "Reports": {
    "Productivity": [
      {
        "name": "Productivity Summary",
        "value": "Productivity"
      },
      {
        "name": "Time Summary",
        "value": "TimeSummary"
      }
    ]
  }
}

非常感谢任何帮助或建议。

谢谢

最佳答案

确保工厂和 Controller 位于同一个应用程序中。 我在工厂做了一些重构,以便它更加可重用。 如果工厂有小改动。现在 getReports 将返回一个 promise 。当 Promise 得到解决时,我们可以调用我们的函数。

var Services = angular.module('Services', ['ngResource']);
Services.factory('reportFactory', function($http){
    console.log(REPORT_LIST_URL);
    return{
        getReports: function(){
            return $http.get(REPORT_LIST_URL); //returning promise
        }
    }
});

Services.controller('ReportsCtrl',function($scope, $http, reportFactory) {
    $scope.reportsList = [];
    console.log($scope.reportsList);
    console.log("Get report list from json file");
    console.log("before the factory");
    reportFactory.getReports().then(
    //success callback
     function(data){ 
       $scope.reportsList = data;
    },
    //error callback
    function(data){
       $scope.reportsList = data;
    });
});

希望这对您有帮助,谢谢。

关于javascript - angularjs 类型错误 : undefined is not a function factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952049/

相关文章:

c# - 检查用户是否在 Orchard CMS 中获得授权

javascript - 带有垂直下拉 CSS 的 Bootstrap 水平导航栏

json - 使用 Postgres 查询 JSONB

javascript - SyntaxError : JSON. 解析:JSON 数据的第 1 行第 1 列出现意外字符

php - 将 MySQL 输出解析为 JSON 提取字段名称

angularjs - (初学者)如何处理 Angular 方式的滚动

javascript - 在 Chrome 开发者工具中调试 AngularJS?

javascript - Webpack 缺少模块 'Module Not Found'

javascript - 突出显示扩展到多行/列的全日历事件

javascript - meteor HTTP "GET"调用