javascript - Angular service and watching a variable -


i have angular service gets $http promise factory making rest call, works fine.:

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 back");                         svcdata.u = data.data;                     });                 });             }             return svcdata.u;         }  ... snipped ... 

in controller, do:

$scope.$watch($scope.user, function(newuser){     console.log($scope.user);     console.log("user here");     dosomestuff(); }); $scope.user = userservice.getuser(); 

the problem watch gets fired when first assign $scope.user (it null), console message "request back" watch function not fire again.

why, , how do this?

  1. pass string $watch()

    $scope.$watch('user', ... 
  2. break function when newuser invalid (null / undefined)

    if (!newuser){   return; } 
  3. use promises

    convert getuser() function return promise.

    for instance, 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 {        // user cache. using timeout simulate http response taking 2.5 seconds        $timeout(function() {          cacheduser = {           name: 'mr user'         };          def.resolve(cacheduser);        }, 2500);     }      return def.promise;   } }); 

for example:

$scope.$watch('user', function(newuser) {    if (!newuser){     return;   }    dosomestuff(); });  userservice.getuser()     .then(function(user){          $scope.user = user      }); 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -