Angular.js: how to call a service once for all the app controllers

后端 未结 2 1939
醉酒成梦
醉酒成梦 2021-01-21 18:59

I don\'t know if this is even one of the Angular concepts or possible to do but i have a service that call the user information (name, id, age, ...):

.factory(\'         


        
2条回答
  •  执笔经年
    2021-01-21 19:33

    I do something similar all the time with services by setting the value to the service once it's returned the first time. Now once the data is set in the service it will return the stored user data instead of making a request to your server.

    service('myService', function($q, $http) {
      this.data;
      var self = this;
    
      this.getMyData = function() {
        if (angular.isDefined(self.data)) {
          // use $q to return a promise
          return $q.when(self.data)
        }
        return $http.get('myurl').then(function(resp) {
          self.data = resp;
        })
      }
    
    }
    

    In your controller you can call myService.getMyData()

提交回复
热议问题