角度服务和观察变量

时间:2016-06-11 11:44:40

标签: javascript angularjs

我有一个角度服务从工厂发出一个$http承诺进行REST调用,效果很好。

var UserService = function($cookies, DataFactory, jsonHelper, $q) {
    var USER_KEY = 'user';
    var USERNAME_KEY = 'username';

    var svcData = {
        u: null,
        b: null,
    }

    var service = {
        setUser : function(user){
            svcData.u = user;
            $cookies.put(USER_KEY, user.id);
        },
        getUser : function(){
            if(svcData.u === null){
                DataFactory.getPrincipalName().then(function(adata){
                    DataFactory.getBDUser(adata.data.username).then(function(data){
                        var reg = {};
                        jsonHelper.setupRegistry(data.data,
                                                 reg);
                        jsonHelper.resolveReferences(
                            data.data, reg, 5);
            console.log("Request is back");
                        svcData.u = data.data;
                    });
                });
            }
            return svcData.u;
        }
 ... snipped ...

在我的控制器中,我这样做:

$scope.$watch($scope.user, function(newUser){
    console.log($scope.user);
    console.log("USER HERE");
    doSomeStuff();
});
$scope.user = UserService.getUser();

问题是当我第一次分配$scope.user(它为空)时,手表会被触发,然后我收到控制台消息“请求回来了”,但监视功能不会再次触发。

为什么,我该怎么做?

1 个答案:

答案 0 :(得分:1)

  1. 将字符串传递给$watch()

    $scope.$watch('user', ...
    
  2. newUser无效时,
  3. 中断函数(null / undefined)

    if (!newUser){
      return;
    }
    
  4. 使用承诺

    转换getUser()函数以返回promise

    例如,https://plnkr.co/edit/nzq9O0JMTxn1k7FL9We5

    app.service('UserService', function($http, $q, $timeout) {
    
      var cachedUser = null;
    
      return {
        getUser: getUser
      }
    
      function getUser() {
        var def = $q.defer();
    
        if (cachedUser) {
          def.resolve(cachedUser)
        } else {
    
          // get user from cache. using timeout to simulate http response taking 2.5 seconds
    
          $timeout(function() {
    
            cachedUser = {
              name: 'Mr User'
            };
    
            def.resolve(cachedUser);
    
          }, 2500);
        }
    
        return def.promise;
      }
    });
    
  5. 例如:

    $scope.$watch('user', function(newUser) {
    
      if (!newUser){
        return;
      }
    
      doSomeStuff();
    });
    
    UserService.getUser()
        .then(function(user){
             $scope.user = user
         });