好的,所以我试图创建一个Factory,它将调用我的REST api来检索数据。一切都很好,直到我更新到Angular 1.6,这迫使我使用Promises,因此我决定尝试工厂:
var registerApplication = angular.module('applications', ['ajoslin.promise-tracker']);
registerApplication.factory('HTTPFactory', ['$http', function dataService($http) {
var applications = {};
applications = function getApplications() { $http ({
'url': '/adminapi/getApplications',
'method': 'GET',
'cache' : true
}).then(function(response){
// return response.data;
console.log(response);
return response;
});
}
return applications;
}]);
registerApplication.controller("ApplicationController", ['HTTPFactory', function ($scope, HTTPFactory) {
$scope.applications = {};
getApplications();
// when landing on the page, get all applications and show them
function getApplications() {
HTTPFactory.getApplications().then(function(response){
$scope.applications = response;
});
}
}]);
但是我收到了这个错误: angular.js:10859错误:undefined不是对象(评估'HTTPFactory.getApplications')
我尝试了几种方式,似乎都给了我某种形式的错误,我做错了什么?
答案 0 :(得分:1)
Password
未正确注入。
Factory
应该是
registerApplication.controller("ApplicationController", ['HTTPFactory', function ($scope, HTTPFactory) {
此外,需要修复以下代码。
registerApplication.controller("ApplicationController", ['$scope', 'HTTPFactory', function ($scope, HTTPFactory) {
应该通过修复闭包问题来替换,并从工厂的逻辑中删除applications = function getApplications() {
// Logic
}
。
.then()
答案 1 :(得分:1)
首先像这样改变工厂
registerApplication.factory('HTTPFactory', ['$http', function ($http) {
var applications = {
getApplications : getApplications
};
function getApplications() {
return $http ({
'url': '/adminapi/getApplications',
'method': 'GET',
'cache' : true
})
}
return applications;
}])
你不必在工厂内写下承诺,只需将http req返回给控制器并在那里捕获承诺。
在控制器中将字符串范围添加到数组
registerApplication.controller("ApplicationController", ['$scope','HTTPFactory', function ($scope, HTTPFactory) {
registerApplication.controller("ApplicationController", ['$scope','HTTPFactory', function ($scope, HTTPFactory) {
$scope.applications = {};
getApplications();
// when landing on the page, get all applications and show them
function getApplications() {
HTTPFactory.getApplications().then(function(response){
$scope.applications = response;
});
}
}])