我一直在努力编写一个返回用户名的服务。
var username, $promise;
angular.module('TestApp').factory('UserService', function($http) {
$promise= $http.get('/api/getuser')
.success(function(data) {
username = data;
});
$promise.then(function() {
return username;
});
});
但是在控制器中注入此服务将返回未定义的值
angular.module('TestApp')
.controller('UserLoginController', function($scope, UserService){
console.log("Username is: "+ UserService);
});
我已确认http get请求返回有效的用户名值。我对角度很新,如果有人能指出我在这里做错了什么,我会非常感激。
答案 0 :(得分:1)
上面的代码看起来像意大利面条。这是一个应该做你想做的基本工厂:
app.factory('UserService', [ '$http', function($http){
var userService = {};
userService.getUser = function(){
return $http.get('/api/getuser').then(function(res){
return res.data;
},function(error){
console.log(error);
return [];
});
}
return userService;
}]);
然后在控制器中调用它:
app.controller('MyController', ['$scope', 'UserService', function($scope,UserService){
$scope.user = {};
UserService.getUser().then(function(data){
$scope.user = data.users[0];
});
}]);
这假定您的API返回的json格式类似于{ users: [{ id: "34534534",name: "John" }] }
。
请注意,我是在飞行中写的,并没有尝试过。它应该工作。
警告:我刚编辑了我的代码以修复一些错误。