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

后端 未结 2 1940
醉酒成梦
醉酒成梦 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:21
    //Assume Value1 and Service1 have been correctly injected
    if (Value1.data === null) {
         Your_Var = Service1.call;
    } else {
        Your_Var = Value1.data;
    } 
    

    For simplicity sake I would put that in a ternary expression when implementing.

    For DRY compliance.

    Going with DRY we need a SharedFactoryFuncion to handle $http requests

    Your_Var = Service1.call;
    //Inside Service1.call
    return Value1.data === undefined ? SharedFactoryFuncion.get("url") : Value1.data;
    

    There are numerous ways to handle the return of data from .get() so I won't go there as it's not pertinent.

    0 讨论(0)
  • 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()

    0 讨论(0)
提交回复
热议问题