我正在使用 Web API 编写我的第一个 Angular 应用程序,但我在从工厂调用函数时遇到了一些问题。
我有两个看起来像这样的工厂:
main.factory('Table', function ($http, $log) {
return {
build: function (token, cubeid) {
return $http({
method: 'POST',
url: 'http://localhost:50051/api/structure/cube',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { token: token, cubeId: cubeid }
});
}
};
});
main.factory('Login', function ($http, $log) {
return {
authorize: function (username, password) {
return $http({
method: 'POST',
url: 'path/to/api/',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { username: username, password: password }
});
}
};
});
还有两个看起来像这样的 Controller :
main.controller('loginController', ['$scope', '$log', '$http', '$location', 'Login', function jobListController($scope, $log, $http, $location, Login) {
$scope.login = function () {
Login.authorize($scope.username, $scope.password).success(function (response) {
$location.path('/table/'+response.token);
});
}
}]);
main.controller('tableController', ['$scope', '$routeParams', '$log', '$http', 'Table', function tableController($scope, $routeParams, $log, Table) {
var cube = 130;
var token = $routeParams.token;
$log.log($routeParams.token);
Table.build(token, cube).success(function (response) {
$scope.structure = response;
$log.log(response);
});
}]);
由于某种原因,构建函数会引发一个错误,提示“TypeError:Table.build 不是一个函数”,而授权函数的工作就像一个魅力。
谁能向我解释为什么构建功能不起作用?
PS:我已经检查过 token 实际上已传递给 Controller 。
最佳答案
你向你的 Controller 注入(inject)不同的服务/工厂
['$scope', '$routeParams', '$log', '$http', 'Table',
function tableController($scope, $routeParams, $log, Table)
应该是
['$scope', '$routeParams', '$log', '$http', 'Table',
function tableController($scope, $routeParams, $log, $http, Table)
关于javascript - TypeError: Factory.function 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30849110/