2016-08-09 45 views
5

我是Angular的新手。我正在學習配置塊並運行模塊塊。Angular中提供者和實例有什麼區別?

請看看下面的代碼:

angular.module('myModule', []). 
config(function(injectables) { // provider-injector 
// This is an example of config block. 
// You can have as many of these as you want. 
// You can only inject Providers (not instances) 
// into config blocks. 
}). 
run(function(injectables) { // instance-injector 
// This is an example of a run block. 
// You can have as many of these as you want. 
// You can only inject instances (not Providers) 
// into run blocks 
}); 

正如你可以在配置塊被寫入看到:「你只能注入提供商(不是實例)」。

這是什麼意思?任何人都可以解釋提供者和實例之間有什麼區別?

回答

4

其實你的問題是好的。爲了使它非常簡單,我們在Angular JS中定義服務來實現我們的功能。 Provider是配置服務應該如何工作的方式之一。在Angular JS中還有一些更多的概念,即值,常量,工廠,服務和裝飾器,它們可以幫助我們以不同的方式攔截服務。請檢查下面的鏈接。

https://docs.angularjs.org/guide/providers

說回提供商,它們被用來定義需要甚至在應用程序啓動到完成的應用程序範圍的配置。由於配置塊在Angular JS模塊加載之前執行,我們在它們下面配置提供者。由於模塊在那段時間之前不會被加載,因此您無法訪問配置塊中的服務。

一旦所有模塊都被$注入器加載,就會執行運行塊。一旦你進入一個運行模塊,你不能再配置你的提供者,因爲你的服務將被加載。這就是您無法在運行塊內訪問提供程序的原因。

我們來看一個例子。我設計了我的應用程序來支持用戶和管理員屏幕。但是與它們相關的功能是在它們各自的服務中定義的。我想在用戶登錄時僅加載相應的服務。我們使用以下提供者來實現該目標。

定義rolesProvider

myApp.provider("roles", function rolesProvider(){ 
var role; 
this.setRole = function(value) { 
role = value; 
} 

this.$get = function rolesFactory() { 
if(role === "user") { 
return new userRole(); 
} else { 
return new adminRole(); 
} 
} 
}); 

配置rolesProvider爲用戶

myApp.config(["rolesProvider"], function(rulesProvider){ 
rulesProvider.setRole("user"); 
}); 

我的應用程序將被配置爲一個用戶,而不是作爲一個管理應用程序時揭開序幕運行。

讓我知道你是否需要更多的解釋。

+0

謝謝......它幫助我理解。 – RajSharma

+0

不客氣。 –

0

從這篇文章中偷取:AngularJS: Service vs provider vs factory - 絕對值得閱讀,以便更好地理解angular中不同類型提供者的角色。

但是如果我們想在注入之前配置Greeter類呢?然後,我們可以寫

例如:

provide.provider('greeter2', function() { 
    var salutation = 'Hello'; 
    this.setSalutation = function(s) { 
    salutation = s; 
} 

    function Greeter(a) { 
    this.greet = function() { 
     return salutation + ' ' + a; 
    } 
    } 

    this.$get = function(a) { //When injected into a controller or service, this is what will get called. 
    return new Greeter(a); 
    }; 
}); 

然後你可以配置上面,像這樣:

angular.module('abc', []).config(function(greeter2Provider) { //Provider injected 
    greeter2Provider.setSalutation('Halo'); 
}); 

function Controller(greeter2) { //Accessing the actual service exposed by the provider.$get 
    expect(greeter2.greet()).toEqual('Halo 123'); 
} 
0

快速回答:提供者將創建一個實例。直到他們可以在config()塊中使用它們。對於想要在啓動期間將url端點更改爲數據提供者的數據提供者非常有用。

但是在運行new Something()之前,您可以在「Provider provider」部分運行一些配置代碼。

服務服務,服務工廠和服務值都是提供程序定義的快捷方式,但隱藏配置部分遠離您並直接轉到對象的實例化(使用new Something())。

相關問題