让其他控制器访问api调用数据

时间:2015-04-24 16:48:01

标签: angularjs

我想做的是:

  1. 应用程序运行后立即进行api调用(使用Process p = new Process(); p.StartInfo = new ProcessStartInfo("/bin/ls", "-l") { RedirectStandardOutput = true, UseShellExecute = false }; p.Start(); p.WaitForExit(); //The output of the shell command will be in the outPut variable after the //following line is executed var outPut = p.StandardOutput.ReadToEnd(); 并从http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/获取想法)
  2. 全球存储数据'这样我的其他控制器就可以访问数据了
  3. 完成api调用并且所有控制器都已解决后,显示用户界面(我不想要任何加载内容的闪存)
  4. 我知道我可以创建一个角度服务来在每个控制器中进行api调用,但如果我在页面上有2个控制器,我不想做出2个相同的请求。

    在下面的示例中,我有ui-router,需要访问nav.controller.js

    home.config.js

    myData

    home.controller.js

    angular.module('myApp')
      .config(['$stateProvider', '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {
    
          $urlRouterProvider.otherwise('/');
    
          $stateProvider
            .state('home', {
              url: '/',
              templateProvider: function($templateCache) {
                return $templateCache.get('home.client.view.html');
              },
              resolve: {
                myService: 'myApiService',
                myData: function(myApiService){
                  return myService.get().$promise;
                }
              },
              controller: 'HomeCtrl as home'
            });
        }
      ]);
    

    nav.controller.js

    angular.module('myApp')
      .controller('HomeCtrl', ['myData',
        function(myData){
          var self = this;
    
          // YAY WORKS!
          console.log(myData);
        }
      ]);
    

    another.controller.js

    angular.module('myData')
      .controller('NavCtrl', ['$scope', 'myData',
        function($scope, myData) {
          // BOO DOESN'T WORK
          console.log(myData);
        }
      ]);
    

1 个答案:

答案 0 :(得分:0)

您仍应使用服务。但是,此服务不应该只进行API调用 - 它还应该存储数据。您的代码看起来像

<强> home.controller.js

angular.module('myApp')
  .controller('HomeCtrl', ['myService',
    function(myService){
      var self = this;

      // YAY WORKS!
      console.log(myService.myData);
    }
  ]);

<强> nav.controller.js

angular.module('myData')
  .controller('NavCtrl', ['$scope', 'myService',
    function($scope, myService) {
      // BOO DOESN'T WORK
      console.log(myService.myData);
    }
  ]);

<强> another.controller.js

angular.module('anotherModule')
  .controller('AnotherCtrl', ['$scope', 'myService',
    function($scope, myService) {
      // BOO DOESN'T WORK
      console.log(myService.myData);
    }
  ]);

myService.get()函数中,您将返回的数据存储在myData