我是AngularJS的新手,并且一直试图从工厂获得JSON几天。我一直得到同样的错误,但没有给我太多信息:
TypeError: Cannot read property '1' of null
我的模块:
var app = angular.module('app', ['ngRoute']);
这是我的控制器:
app.controller('homePageController', function ($scope, projectsFactory) {
$scope.projects = projectsFactory.getList();
});
这是我的工厂:
app.factory('projectsFactory', function($http, $q) {
return {
getList: function() {
var deferred = $q.defer();
$http.get('Resources/JSON/projects.json').success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
},
};
});
以下是部分页面:
<ul ng-controller="homePageController">
<li ng-repeat="project in projects">
{{projects.name}}
</li>
</ul>
这是JSON本身:
[
{
"Id": 1,
"name": "Colombo Law",
"snippet": "Colombo Law snippet"
},
{
"Id": 2,
"name": "Lunch?",
"snippet": "What for lunch snippet"
}
]
以下是我收到的完整错误消息:
TypeError: Cannot read property '1' of null
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:6839:28)
at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js:907:26)
at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:6271:13)
at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:5682:15)
at publicLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:5587:30)
at boundTranscludeFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:5701:21)
at controllersBoundTransclude (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:6292:18)
at update (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js:865:25)
at Scope.$get.Scope.$broadcast (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js:12329:28)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js:556:26 <div ng-view="" class="ng-scope">
任何帮助将不胜感激!
答案 0 :(得分:1)
较新版本的角度不会自动解析承诺。您的项目工厂正在返回承诺而不是实际列表,并且ng-repeat将不会对承诺起作用。
我相信您需要做的是将promise的结果分配给您的范围变量,如下所示:
app.controller('homePageController', function ($scope, projectsFactory) {
projectsFactory.getList().then(function(projects) {
$scope.projects = projects;
});
});