Angular.js:如何调用一个服务,一旦所有的应用程序控制器 [英] Angular.js: how to call a service once for all the app controllers

查看:119
本文介绍了Angular.js:如何调用一个服务,一旦所有的应用程序控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是连的角的概念之一,或可能这样做,但我有调用用户信息(姓名,身份证,年龄,...)服务:

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('me', function($resource, API_URL, $q) {
    return {
        getUser: function() {
            var deferred = $q.defer();
            var url = API_URL + 'api/me';
            $resource(url)
                .get(function(user) {
                    deferred.resolve(user);
                }, function(response) {
                    deferred.reject(response);
                });
            return deferred.promise;
        }
    };
})

我用在许多控制器此服务来获得用户数据,并用它来与其他<$发送C $ C> HTTP 来电。例如在我的 newItemCtrl

I use this service in many controllers to get the user data and use it to send with other http calls. for example in my newItemCtrl

.controller('newItemCtrl', function($scope, $http, API_URL, me) {

我叫服务,因为我在很多其他控制器没有

i called the me service as i did in many other controllers

,我想知道有没有办法只有一次调用这个服务,并在每个控制器使用它在所有的控制器,而不是x次

and am wondering is there a way to call this service only once and use it in all the controllers instead of x times in each controller

推荐答案

我通过一旦它返回的第一时间值设置为服务的服务类似的东西所有的时间。现在,一旦数据在服务设置将返回存储的用户数据,而不是发出请求到服务器的。

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;
    })
  }

}

在你的控制器可以调用 myService.getMyData()

In your controller you can call myService.getMyData()

这篇关于Angular.js:如何调用一个服务,一旦所有的应用程序控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆