从服务中获取值,从控制器中的另一个控制器传递角度

时间:2015-11-25 05:43:02

标签: angularjs

对于共享多个控制器的服务中的数据存在一些问题。在下面的示例中,在登录期间,我将UserService.signedInUser设置为登录的当前用户对象。在主页面中,我尝试使用它的值,但它给出了undefined。由于主页总是在用户签名之后得到,我希望设置UserService.signedInUser值,但不确定为什么它表示未定义..我想这与异步性有关,我可以使用promise但是可以'好吧..有人可以就此提出建议吗?什么是使服务器中的值始终可供控制器使用的好策略? ..appreciated。

//in login controller
.controller('LoginCtrl', function (Auth, $location, UserService){
   login.signIn2Facebook = function() {  

    Auth.$authWithOAuthPopup("facebook")
      .then(function(authData){
        console.log('successfully logged in, ', authData);

        //put the user in the DB.
        console.log('sending the user info to the DB');
        UserService.postUser(authData).then(function (data){
          // console.log('POST promise data', data);
          //here setting value to the service property.
          UserService.signedInUser = data; //this sets here okay.
        });

      })
      .catch(function(err){
        if(err) {
         console.log("Authentication failed!!", err);
        }
      })
  };
}

//in main page controller
.controller('HomeCtrl', function (UserService){
  //I want to get the value of currently signedin user.
  var signedInUserGender = UserService.signedInUser.gender;
  console.log('signedInUserGender>>>>',UserService.signedInUser); //this gives undefined.

  //only get ones with opposite gender
  if(signedInUserGender === 'male'){ //signed in user is male
    UserService.getUsers('female').then(function (data){
      // console.log(data);
      home.users = data;
      home.currentOne = home.users[count];
    });
  } else { //signed in user is female
    UserService.getUsers('male').then(function (data){
      // console.log(data);
      home.users = data;
      home.currentOne = home.users[count];
    });
  }
}

//service code
.factory('UserService', function ($q, $http){
  var userService = {};
  userService.signedInUser = {};

  userService.getUsers = function(gender) {
    //this gets all users with the gender from DB.
  };

  userService.postUser = function(authData) {
   //this do POST request to the server to create a user
  };

  userService.saveFavorite = function(id, currentUser){
    //this will do PUT request to the server to update the current user's favorite
  }

  return {
    getUsers: userService.getUsers,
    postUser: userService.postUser,
    saveFavorite: userService.saveFavorite,
    signedInUser: userService.signedInUser 
  }
})

1 个答案:

答案 0 :(得分:1)

问题是您的各种命令正在更新数据,但Angular不会立即意识到更改,因此不会运行摘要周期。因此,当你使用angular.copy时,你会让角度知道;您也可以使用$scope.$apply$timeout,或者您可以使用$ emit消息告诉其他控制器更新其信息