我在这里有一个新手问题。
我在angularJS编码工厂。有了它,我希望有一个用户列表,还有一个填充它的方法。
所以这是我的代码......
工厂
app.factory("usuariosFactory", function ($http) {
var f = {};
f.users = [];
f.getUsers = function (callback) {
var token = window.localStorage.getItem("_token");
$http.get("http://localhost:8000/api/user/list?token=" + token).then(function (response) {
f.users = response.data.users;
/* the console.log outputs OK with the users from the server */
console.log(f.users);
});
};
return f;
});
控制器
app.controller("usuariosController", function ($scope, usuariosFactory) {
var scope = this;
/* link users from factory to controllerś scope .. NOT WORKING */
usuariosFactory.getUsers();
scope.usuarios = usuariosFactory.users;
});
我现在正打着我的头。我不明白如何实现这一目标。
答案 0 :(得分:1)
您应该promise
factory
到controller
controller
然后在subscribe
中,您promise
应scope variable
并将数据分配给app.factory("usuariosFactory", function ($http) {
var f = {};
f.users = [];
f.getUsers = function (callback) {
var token = window.localStorage.getItem("_token");
return $http.get("http://localhost:8000/api/user/list?token=" + token);
};
return f;
});
<强>工厂:强>
app.controller("usuariosController", function ($scope, usuariosFactory) {
var scope = this;
usuariosFactory.getUsers().then(function (response) {
scope.usuarios = response.data;
});
});
<强>控制器:强>
{{1}}
答案 1 :(得分:-1)
由于内部有usuariosFactory.getUsers
,$http.get
是一个异步函数。因此,要获得数据,您必须使用已经放在getUsers
中的回调函数。代码应该是:
usuariosFactory.getUsers(function () {
scope.usuarios = usuariosFactory.users;
});
并且在f.users = response.data.users;
之后你必须调用回调函数。像这样:
f.getUsers = function (callback) {
var token = window.localStorage.getItem("_token");
$http.get("http://localhost:8000/api/user/list?token=" + token).then(function (response) {
f.users = response.data.users;
callback();
});
};
通过这种方式,您将使用回调函数处理异步函数。另一种方法是使用promises,这样你的代码应该是这样的:
工厂
app.factory("usuariosFactory", function ($http, $q) {
var f = {};
f.users = [];
f.getUsers = function (callback) {
var token = window.localStorage.getItem("_token");
var deferred = $q.defer(); // Creates the object that handles the promise
$http.get("http://localhost:8000/api/user/list?token=" + token)
.then(function (response) {
f.users = response.data.users;
deferred.resolve('You can pass data!'); // Informs that the asynchronous operation have finished
});
return deferred.promise; // Returns a promise that something will happen later
};
return f;
});
控制器
app.controller("usuariosController", function ($scope, usuariosFactory) {
var scope = this;
// Now you can use your function just like you use $http
// This way, you know that watever should happen in getUsers, will be avaible in the function
usuariosFactory.getUsers()
.then(function (data) {
console.log(data) // Print 'You can pass data!'
scope.usuarios = usuariosFactory.users;
});
});