Javascript TypeError:无法读取属性';注:项目服务&x27;未定义的
我正在尝试在控制器中加载一个对象,该对象应该在我的服务(工厂)notesFactory中可用 但是,控制器根本无法识别注入的服务。您可以查看返回“undefined”的语句console.log(notesFactory的类型),因此notesObjectInService会触发异常 我不知道我错过了什么。我不认为这只是一个输入错误(我检查了几次代码),但我对javascript和AngularJS还不熟悉,所以我可能遗漏了一些东西。我想知道这个问题是否会存在于后承诺中,但我仍然难以确切理解这些承诺是如何起作用的 如果有人知道这个问题的答案,我将非常感激Javascript TypeError:无法读取属性';注:项目服务&x27;未定义的,javascript,angularjs,Javascript,Angularjs,我正在尝试在控制器中加载一个对象,该对象应该在我的服务(工厂)notesFactory中可用 但是,控制器根本无法识别注入的服务。您可以查看返回“undefined”的语句console.log(notesFactory的类型),因此notesObjectInService会触发异常 我不知道我错过了什么。我不认为这只是一个输入错误(我检查了几次代码),但我对javascript和AngularJS还不熟悉,所以我可能遗漏了一些东西。我想知道这个问题是否会存在于后承诺中,但我仍然难以确切理解这些
function NotesProvider(){
this.$get= angular.noop
}
angular.module('theNotesApp2',['ui.router'])
.config(['$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '',
//the templateUrl value is the id for the routing
templateUrl: '/home.html',
controller: 'mainCtrl',
resolve: {
postPromise: ['notesFactory', function(notesFactory){
return notesFactory.getAll();
}]
}
})
.state('navbar',{
url: '/navbar',
templateUrl: '/navbar.html',
controller: 'mainCtrl'
})
.state('notes',{
url: '/notes/{id}',
templateUrl: '/notes.html',
controller: 'notesCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('notesFactory', NotesProvider,'$http' [function($http, NotesProvider){
var notas = {notesObjectInService: []};
notas.getAll() = function() {
return $http.get('/notes.json').success(function(data){
angular.copy(data, notas.notesObjectInService);
})
};
notas.create() = function(note){
return $http.post('/notes.json', note).success(function(data){
notas.notesObjectInService.push(data);
})
};
return notas;
}])
.controller('mainCtrl',['$scope', 'notesFactory', function($scope, notesFactory){
console.log(typeof notesFactory);
$scope.notes = notesFactory.notesObjectInService;
$scope.addNote = function(){
if ($scope.title === "" ) {
return;
}
notesFactory.create({
title: $scope.title,
body:$scope.body
});
$scope.title= '';
$scope.body= '';
};
}])
.controller('notesCtrl', ['$scope', 'notesFactory', '$stateParams', function(
$scope, notesFactory, $stateParams){
console.log('test');
$scope.note =
notesFactory.notesObjectInService[$stateParams.id]
}])
这里有几个问题。首先,您混淆了工厂定义中的数组表示法和注入服务的顺序 那么对象方法定义应该在方法名称之后不带
()
:
notas.getAll = function () { /* ... */ };
正确的工厂定义如下所示:
.factory('notesFactory', ['$http', 'NotesProvider', function ($http, NotesProvider) {
var notas = {
notesObjectInService: []
};
notas.getAll = function () {
return $http.get('/notes.json').success(function (data) {
angular.copy(data, notas.notesObjectInService);
})
};
notas.create = function (note) {
return $http.post('/notes.json', note).success(function (data) {
notas.notesObjectInService.push(data);
})
};
return notas;
}]);
我想这里的错误
.factory('notesFactory',NotesProvider,'$http'[函数($http,NotesProvider){
谢谢@dfsq它解决了这个问题。我没有意识到我犯了那个愚蠢的错误。而且,一旦数组表示法正确完成,“NotesProvider”就变得毫无意义,代码现在可以正常工作了。