2014-09-03 61 views
6

我在我的角度應用程序中使用角度路由段,並嘗試從json提要配置段。

我有這個問題,因爲我不知道如何注入$httpapp.config函數。這種失敗Unknown provider: $http

myApp.config(["$http", "$routeSegmentProvider", function ($http, $routeSegmentProvider) { 
    /* setup navigation here calling $routeSegmentProvider.when a number of times */ 
} 

因此,而不是注入$ HTTP到config,我也試過注射$routeSegmentProvidermyApp.run

myApp.run(["$http", "$routeSegment", function($http, $routeSegment) { 
    /* can use $http here to get data, but $routeSegment is not the same here */ 
    /* $routeSegment does not have the when setup method */ 
}]); 

我也試過

myApp.run(["$http", "$routeSegmentProvider", function($http, $routeSegmentProvider) 

,但我得到Unknown provider: $routeSegmentProviderProvider <- $routeSegmentProvider

+0

你可以在這裏找到你的答案:http://stackoverflow.com/questions/15937267/inject-service-in-app-config – 2014-09-03 12:17:17

+0

@DavidBohunek我想我以前遇到過這個例子,但我無法讓它工作出於某種原因。我決定現在與cliff.meyers一起回答。 – gwin003 2014-09-03 12:41:45

回答

11

Provi只能在「配置」階段注入ders,而不能在「運行」階段注入。相反,諸如$ http之類的服務在「配置」階段尚未初始化,只能在「運行」階段使用。

一個小技巧來解決,這是定義在父功能範圍變量,因此,無論是「配置」和「運行」塊可以訪問它:

var routeSegmentProvider = null; 

myApp.config(["$routeSegmentProvider", function ($routeSegmentProvider) { 
    routeSegmentProvider = $routeSegmentProvider; 
}]); 

myApp.run(["$http", function($http) { 
    // access $http and routeSegmentProvider here 
}]); 

我不是當然,如果你在運行階段嘗試調用$ routeSegmentProvider.setup()時遇到問題,我還沒有嘗試過。在過去,我能夠使用相同的技術來註冊依賴於$ httpProvider的一些自定義服務的http響應攔截器。

+2

它的工作原理,雖然這可能不是最好的*解決方案...我決定現在就去。謝謝! – gwin003 2014-09-03 12:42:47

+0

看起來像一個黑客使用全局變量..你們大多數人會讓這個滑,因爲它是前端JS。 – 2015-12-16 17:14:34

+1

此代碼最初包裝在IIFE中,但爲簡潔起見,我省略了它。沒有什麼需要使用全局作用域,它只是通過關閉來訪問。 – 2016-06-02 15:29:13