我有以下工厂:
app.factory('clientFactory', function ($http) {
var factory = {};
factory.getClients = function () {
var url = "/tracker/api/client";
$http.get(url).then(function (response) {
return response.data;
});
};
factory.getClient = function (id) {
// TODO
};
factory.insertClient = function (firstName, lastName, city) {
// TODO
};
factory.deleteClient = function (id) {
// TODO
};
return factory;
});
Controller :
app.controller('ClientController', function ($scope, clientFactory) {
$scope.clients = [];
init();
function init() {
$scope.clients = clientFactory.getClients();
}
$scope.insertCustomer = function () {
// TODO
};
$scope.deleteCustomer = function (id) {
// TODO
};
});
在我的 Controller 中,“客户端”始终为空。我尝试了其他几种方法,例如我所看到的 here但我收到一个错误“不能在 null 上调用成功”,如果我克服了该错误,我的成功函数将永远不会被调用。
我在这里缺少什么?
最佳答案
在您的 Controller 中,您将 getClients
方法视为同步方法。请记住,当您执行 $http.get
时,会返回一个 promise 。您需要将该 Promise 返回给 Controller ,以便它可以使用处理成功结果的方法调用 .then
。
您的 getClients
方法需要如下所示:
factory.getClients = function () {
var url = "/tracker/api/client";
return $http.get(url);
};
我相信您的 init
方法需要如下所示:
function init() {
clientFactory.getClients().then(function(response) {
$scope.clients = response.data;
});
}
尝试一下!
关于javascript - 使用工厂和 Controller 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559054/