2016-06-16 36 views
2

如何將服務注入到我的路由器中,以便其結果(json)將在整個應用程序中可用?Angular js。在路由器中注入服務

路由器:

export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider, MainController, ConfigService) { 

$stateProvider.state('home', { 
    url: '/', 
    controller: 'MainController', 
    resolve: { 

     /* @ngInject */ 
     someResolve: (ConfigService) => 
     ConfigService.config() 
    } 
}); 

$urlRouterProvider.otherwise('/'); 
}]; 

服務:

export default function ConfigService() { 
return ['$http', function($http) { 

    this.config = function() { 
     return $http({ 
      url: '../json/config.json', 
      method: 'GET' 
     }).then(function(result) { 
      console.log(result); 
     }); 
    }; 
}]; 
} 

Maincontroller

export default function MainController() { 
return ['$scope','$location','ConfigService','$window', function($scope, $location, ConfigService, $window) { 

    ConfigService.config(); 

}]; 
} 
+0

如果你要存儲此JSON做?例如在$ rootScope中,一個全局變量,一個帶有getter等服務的局部變量? –

+0

我希望它被存儲,以便整個應用程序可以從一開始就訪問它。那怎麼做對我來說並不重要。 – user2952238

回答

1

的MainController和ConfigService的沒有任何提供商指定......你的說法應該是像

export default ['$stateProvider', '$urlRouterProvider','MainController', 'ConfigService', function($stateProvider, $urlRouterProvider, MainController, ConfigService) {} 
+0

我已經編輯了我的代碼。看到第一篇文章。 – user2952238

+1

仍然這個問題仍然是相同的爲您的路由器...只是用此代碼替換您的路由器的第一行... –

+0

謝謝,但後來我得到:「$ injector:unpr]未知的提供者:MainController」 – user2952238

0

做它的決心。

$stateProvider.state('home', { 
    url: '/', 
    controller: 'MainController', 
    resolve: { 

     /* @ngInject */ 
     someResolve: (ConfigService) => 
     ConfigService.config() 
    } 
}); 

那麼你「的ConfigService」可被注入到所述控制器,和使用(在配置的結果())。編輯爲使用正確的服務名稱等。

+0

謝謝。我添加你的代碼做我的路由器。但是當我跑了,我沒有從服務中得到任何回報..? – user2952238

+0

它甚至沒有執行''config.json' – user2952238

+0

這就是我所做的。仍然沒有按預期工作。 – user2952238