1

I have been working to write a service to return username.

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;
});
});

But injecting this service in an controller would return in an undefined value

angular.module('TestApp')
.controller('UserLoginController', function($scope, UserService){
console.log("Username is: "+ UserService);
});

I have confirmed that http get request returns valid username value. I am quite new to angular and would really appreciate if anyone can point out what am I doing wrong here.

4

1 回答 1

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];
  });
}]);

这假定 json 格式类似于{ users: [{ id: "34534534",name: "John" }] }您的 API 返回的格式。

请注意,我是即时写的,并没有尝试过。它应该可以工作。

警告:我刚刚编辑了我的代码以修复一些错误。

于 2014-04-21T20:57:15.807 回答