AngularJS:无法访问控制器中的Object属性

时间:2015-12-12 15:13:00

标签: javascript angularjs

这是我从服务中获取的对象。

这是我的控制者。

var user = useroneService.getLoggedUser(user);
console.log(user);

enter image description here

console.log(user.data);

当我尝试访问数据时,我得到了undefined。如何访问Object数据?

user.service.js

'use strict';
angular.module('app').service('userService',['authService', 'userTransformer','LoggedUser', function(authService, userTransformer, LoggedUser) {
  this.getLoggedUser = function(user){
    return authService.login(user).then(function (response) {
      var loggedUser = userTransformer.transform(response.data);
    });
  };
}]);

logged.user.js

angular.module('app').value('LoggedUser', function () {  
    var LoggedUser = function () {
        this.dispalyName = '';
        this.token = '';
        this.logged = false;
    };  
    LoggedUser.prototype = {    
    };
});

user.transformer.js

angular.module('app').factory('userTransformer',['LoggedUser', function (LoggedUser) {
  //logged user transform
  var transformObject = function (response) {
    var model = new LoggedUser();
    angular.extend(model, response);
    return model;
  };
  return {
    transform: transformObject
  };
}]);

AuthService(get data)==>UserService(data transform to LoggedUser using the transformer)
    ==>LoginController

1 个答案:

答案 0 :(得分:1)

你没有回复承诺。将您的控制器代码更改为:

useroneService.getLoggedUser(user).then(function(data) {
    var user = data;
    console.log(user);
})

还有一件事,你没有从服务中返回响应:

return authService.login(user).then(function (response) {
  var loggedUser = userTransformer.transform(response.data);
  return loggedUser; //add this
});