我不明白为什么我的与REST API进行通讯的工厂无法正常工作。我收到以下错误:
TypeError: Cannot read property 'protocol' of undefined
和
TypeError: Cannot read property 'message' of undefined
todo.controller.js
'use strict';
angular
.module('app')
.controller('TodoController', ['$scope', 'todoFactory', function ($scope, todoFactory) {
getTodos();
function getTodos() {
todoFactory.all()
.success(function (todos) {
$scope.todos = todos;
})
.error(function (error) {
$scope.status = 'Unable to load todo data: ' + error.message;
});
}
}]);
todo.factory.js
'use strict';
angular.module('app')
.constant('API_URI', 'http://localhost:8080/api/todo')
.factory('todoFactory', ['$http', function($http, API_URI) {
var todoFactory = {};
function getUrl() {
return API_URI;
}
function getUrlForId(itemId) {
return getUrl + itemId;
}
todoFactory.all = function () {
return $http.get(getUrl());
};
todoFactory.fetch = function (id) {
return $http.get(getUrlForId(id));
};
todoFactory.add = function (todo) {
return $http.post(getUrl(), todo);
};
todoFactory.update = function (todo) {
return $http.put(getUrlForId(id), todo)
};
todoFactory.delete = function (id) {
return $http.delete(getUrlForId(id));
};
return todoFactory;
}]);
但是,如果我将在有效的控制器中调用简单的$ http.get(something):
$http.get('http://localhost:8080/api/todo').
success(function(data) {
$scope.todos = data;
});
与控制器中简单的直接$ http.get()相比,我的工厂用法有什么问题?
使用以下语法(为了支持简化):
.factory('todoFactory', ['$http', function($http, API_URI) {
您还需要添加'API_URI'
为字符串(在旁边'$http'
)
.factory('todoFactory', ['$http', 'API_URI', function($http, API_URI) {
否则,将为该API_URI
参数注入注释。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句