AngularJS Providers 詳解

供應者(Providersimage

Each web application you build is composed of objects that collaborate to get stuff done. These objects need to be instantiated and wired together for the app to work. In Angular apps most of these objects are instantiated and wired together automatically by the injector service.html

你建立的任何 Web 應用都是一些互相依賴的對象組合。這些對象須要被實例化並被綁定在一塊兒工做。在 Angular 應用中,這些對象經過注入器服務自動完成實例化和綁定。ios

The injector creates two types of objects, services and specialized objects.angularjs

注入器建立了兩種類型的對象,services(服務)和 specialized objects(特殊對象)。web

Services are objects whose API is defined by the developer writing the service.spring

服務等同於對象,它的 API 由編寫服務的開發者定義。bootstrap

Specialized objects conform to a specific Angular framework API. These objects are one of controllers, directives, filters or animations.設計模式

特殊對象服從一套專門的 Angular 框架 API。這些對象是控制器、指令、過濾器或動畫效果中的一個。api

The injector needs to know how to create these objects. You tell it by registering a "recipe" for creating your object with the injector. There are five recipe types.瀏覽器

注入器須要知曉如何去建立這些對象。你經過註冊一個「recipe(配方)」 來告訴注入器去建立你的對象。共有五種類型的配方。緩存

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types — Value, Factory, Service and Constant — are just syntactic sugar on top of a Provider recipe.

最繁瑣,也是功能最全面的是 Provider recipe。剩下的四種類型——Value,Factory,Service 和 Constant —— 僅僅是 Provider recipe 的語法糖。

Let's take a look at the different scenarios for creating and using services via various recipe types. We'll start with the simplest case possible where various places in your code need a shared string and we'll accomplish this via Value recipe.

接下來,咱們看看如何在不一樣場景下經過不一樣的 recipe types 建立和使用 services 。咱們將從最簡單的例子開始,經過 Value recipe在代碼中共享一個字符串。

 

 

Note: A Word on Modules

注意:模塊概要

 

In order for the injector to know how to create and wire together all of these objects, it needs a registry of "recipes". Each recipe has an identifier of the object and the description of how to create this object.

爲了讓注入器知曉如何建立和綁定全部的對象,它須要一個"recipes"的註冊表。每一個 recipe 都有惟一的對象標識符和以及何建立這個對象的描述。

Each recipe belongs to an Angular module. An Angular module is a bag that holds one or more recipes. And since manually keeping track of module dependencies is no fun, a module can contain information about dependencies on other modules as well.

每一個 recipe 屬於一個 Angular 模塊。Angular 模塊是一個保存了一個或多個 recipes 的袋子。手動跟蹤模塊依賴關係顯然不是一個好方法,所以一個模塊也能夠包含依賴其它模塊的相關信息。

When an Angular application starts with a given application module, Angular creates a new instance of injector, which in turn creates a registry of recipes as a union of all recipes defined in the core "ng" module, application module and its dependencies. The injector then consults the recipe registry when it needs to create an object for your application.

一個 Angular 應用開始於一個給定的應用模塊時,Angular 會建立一個新的注入器實例,進而按照全部核心"ng"模塊、應用模塊和在它的依賴中統必定義的 recipes 來建立一個 recipes 的註冊表。而後,注入器經過查詢 recipes 註冊表來建立應用所需的對象。

 

 

變量方式(Value Recipe

Let's say that we want to have a very simple service called "clientId" that provides a string representing an authentication id used for some remote API. You would define it like this:

假定咱們想要得到一個很是簡單的 service 叫作"clientId",它提供一個字符串用於表示某些遠程 API 的認證 id。你能夠這樣去定義它:

 myApp = angular.module('myApp''clientId', 'a12345654321x');

Notice how we created an Angular module called myApp, and specified that this module definition contains a "recipe" for constructing the clientId service, which is a simple string in this case.

注意,咱們建立一個名爲 myApp 的 Angular 模塊,而後指定了一個包含構建 clientId service 的配方,這只是一個字符串的簡單例子。

And this is how you would display it via Angular's data-binding:

如下是如何經過 Angular數據綁定來顯示它:

myApp.controller('DemoController', ['clientId', .clientId =<html ng-app="myApp"> 
<body ng-controller="DemoController as demo"></body> 
</html>

In this example, we've used the Value recipe to define the value to provide when DemoController asks for the service with id "clientId".

在這個例子中,咱們使用了 Value recipe 去定義這個 value,提供給 DemoController 請求這個服務的 id "clientId"。

On to more complex examples!

更復雜的例子!

 

 

工廠方式(Factory Recipe

The Value recipe is very simple to write, but lacks some important features we often need when creating services. Let's now look at the Value recipe's more powerful sibling, the Factory. The Factory recipe adds the following abilities:

這個 Value recipe 寫起來很是簡單,但缺少建立 service時常常用到的一些重要特徵。如今讓咱們看看 Value recipe 更強大的兄弟——Factory。Factory recipe 增長了如下能力:

ability to use other services (have dependencies)

可以使用其它的 services(依賴)

service initialization

service 初始化

delayed/lazy initialization

延遲/懶惰初始化

The Factory recipe constructs a new service using a function with zero or more arguments (these are dependencies on other services). The return value of this function is the service instance created by this recipe.

Factory recipe經過一個包含有零個或多個參數(它所依賴的其它 services)的方法構造一個新的 service。這個方法的返回值是由 recipe 建立的這個服務的實例。

Note: All services in Angular are singletons. That means that the injector uses each recipe at most once to create the object. The injector then caches the reference for all future needs.

注意:Angular 中全部的服務都是單例模式。這意味着注入器建立這個對象時,僅使用一次recipe。而後注入器緩存全部未來須要的引用。

Since Factory is more powerful version of the Value recipe, you can construct the same service with it. Using our previous clientId Value recipe example, we can rewrite it as a Factory recipe like this:

由於 Factory 是Value recipe 更強大的版本,你能夠構造和它同樣的服務。使用咱們以前的 clientId Value recipe 的例子,能夠採用 Factory recipe 這樣重寫:

myApp.factory('clientId',  'a12345654321x'

But given that the token is just a string literal, sticking with the Value recipe is still more appropriate as it makes the code easier to follow.

但考慮到令牌僅僅是一個字符串常量,使用 Value recipe 更恰當,也更易於代碼的閱讀。

Let's say, however, that we would also like to create a service that computes a token used for authentication against a remote API. This token will be called apiToken and will be computed based on the clientId value and a secret stored in the browser's local storage:

好比說,咱們想建立一個用於計算遠程 API 認證令牌的服務。這個令牌將被稱作 apiToken,並計算基於 clientId 的值,而後加密存儲於瀏覽器 Local Storage 中:

myApp.factory('apiToken', ['clientId',  encrypt =  (data1 + ':' + secret = window.localStorage.getItem('myApp.secret' apiToken =

In the code above, we see how the apiToken service is defined via the Factory recipe that depends on clientId service. The factory service then uses NSA-proof encryption to produce an authentication token.

在上面的代碼中,咱們看到了如何經過工廠方法定義這個依賴於 clientId 服務的 apiToken 服務。這個工廠服務使用 NSA-proof 加密去產生一個認證令牌。

Note: It is best practice to name the factory functions as <serviceId>Factory (e.g. apiTokenFactory). While this naming convention is not required, it helps when navigating the code base or looking at stack traces in the debugger.

注意:工廠方法命名的最佳實踐相似於<serviceId>Factory (e.g. apiTokenFactory)。雖然這種命名習慣不是必須的,但它有助於代碼庫導航或查看調試器的堆棧跟蹤。

Just like with Value recipe, Factory recipe can create a service of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

與 Value recipe 同樣,Factory recipe 可以建立任何類型的服務,對象常量,方法,甚至一個自定義類型的實例。

 

 

 

服務方式(Service Recipe

JavaScript developers often use custom types to write object-oriented code. Let's explore how we could launch a unicorn into space via our unicornLauncher service which is an instance of a custom type:

JavaScript 開發者經常使用自定義的類型去編寫面向對象的代碼。讓咱們探究如何經過 unicornLauncher 服務發射一個 unicorn(獨角獸)進入太空,這是一個自定義類型的實例:

.launchedCount = 0.launch = .launchedCount++

We are now ready to launch unicorns, but notice that UnicornLauncher depends on our apiToken. We can satisfy this dependency on apiToken using the Factory recipe:

咱們如今來準備發射 unicorn,但請注意 UnicornLauncher 依賴了咱們的 apiToken。咱們可使用 Factory recipe 來知足這個 apiToken的依賴:

myApp.factory('unicornLauncher', ["apiToken",

This is, however, exactly the use-case that Service recipe is the most suitable for.

就是這樣。不過,使用 Service recipe 纔是最爲恰當的例子。

The Service recipe produces a service just like the Value or Factory recipes, but it does so by invoking a constructor with the new operator. The constructor can take zero or more arguments, which represent dependencies needed by the instance of this type.

這個 Service recipe 產生一個相似於 Value 和 Factory recipes ,但它經過調用構造函數去執行 new 操做。這個構造函數能夠接受零或多個參數,表示這個類型實例所需的依賴項。

Note: Service recipes follow a design pattern called constructor injection.

注意:Service recipes 的設計模式被稱之爲構造函數注入。

Since we already have a constructor for our UnicornLauncher type, we can replace the Factory recipe above with a Service recipe like this:

由於咱們已經有了一個 UnicornLauncher 類型的構造函數,就可以像這樣去用 Service recipe 替換 Factory recipe:

myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

Much simpler!

多麼簡單!

Note: Yes, we have called one of our service recipes 'Service'. We regret this and know that we'll be somehow punished for our mis-deed. It's like we named one of our offspring 'Child'. Boy, that would mess with the teachers.

注意:是的,咱們有一個被稱爲「Service」的 service recipes。很遺憾咱們將由於 mis-deed 而遭到報應。這就像是給咱們某一個後代起名叫「小盆友」。這麼搞會讓老師們困惑。

 

供應者方式(Provider Recipe

There are two more recipe types left to cover. They are both fairly specialized and are used infrequently. As already mentioned in the intro, the Provider recipe is the core recipe type and all the other recipe types are just syntactic sugar on top of it. It is the most verbose recipe with the most abilities, but for most services it's overkill.

還有兩個 recipe 類型。它們都至關特殊,不多使用。如前述,Provider recipe 是核心 recipe 類型,全部其餘的配方類型只是基於它的語法糖。它是最詳細功能最多的 recipe,但對於大多數服務來講,它是多餘的。

Provider recipe is syntactically defined as a custom type that implements a $get method. This method is a factory function just like the one we use in Factory recipe. In fact, if you define a Factory recipe, an empty Provider type with the $get method set to your factory function is automatically created under the hood.

Provider recipe 是語法定義爲一個自定義類型,實現 $get 的方法。這個方法是一個工廠方法,就像咱們在 Factory recipe 中使用的同樣。事實上,若是你定義一個 Factory recipe,鉤子會自動建立一個包含空 Provider 類型 $get 方法的工廠方法。

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

只有當你但願一個應用程序配置的 API 必須在應用程序啓動以前被建立,你才應該使用 Provider recipe 。一般只關注可重用服務的行爲可能在應用程序間略有不一樣。

Let's say that our unicornLauncher service is so awesome that many apps use it. By default the launcher shoots unicorns into space without any protective shielding. But on some planets the atmosphere is so thick that we must wrap every unicorn in tinfoil before sending it on its intergalactic trip, otherwise they would burn while passing through the atmosphere. It would then be great if we could configure the launcher to use the tinfoil shielding for each launch in apps that need it. We can make it configurable like so:

咱們假設 unicornLauncher是個很不錯的服務,許多應用程序都在使用它。默認狀況下,launcher 發射 unicorns 進入太空時沒有任何防禦屏蔽。但某些行星的大氣層實在是太厚了,以致於咱們在星際旅行發射以前,必須用錫紙包住每個 unicorns,不然它們將會在穿越大氣層時燒燬。若是咱們能夠按照應用程序的須要去爲 launcher 的每次發射配置使用錫箔屏蔽罩,那就再好不過了。咱們可作以下配置:

myApp.provider('unicornLauncher',  useTinfoilShielding = .useTinfoilShielding = = !!.$get = ["apiToken",

To turn the tinfoil shielding on in our app, we need to create a config function via the module API and have theUnicornLauncherProvider injected into it:

爲了在咱們的應用程序中啓用錫紙屏蔽罩,咱們須要經過模塊的 API 建立一個含有注入 UnicornLauncherProvider 的配置方法:

myApp.config(["unicornLauncherProvider",

 

Notice that the unicorn provider is injected into the config function. This injection is done by a provider injector which is different from the regular instance injector, in that it instantiates and wires (injects) all provider instances only.

請注意 unicorn provider 被注入的配置方法,這種注入是經過 provider 的注入器完成的,不一樣於普通的實例注入器只是由 provider 實例進行實例化和綁定(注入)。

During application bootstrap, before Angular goes off creating all services, it configures and instantiates all providers. We call this the configuration phase of the application life-cycle. During this phase services aren't accessible because they haven't been created yet.

在應用程序啓動期間,Angular 建立的全部服務前,配置和實例化全部的 providers。咱們稱之爲應用程序生命週期中的配置階段。在此階段服務還不可用,由於它們尚未被建立。

Once the configuration phase is over, interaction with providers is disallowed and the process of creating services starts. We call this part of the application life-cycle the run phase.

配置階段結束,providers 交互被禁止,開始建立 services。咱們稱這一階段爲應用程序生命週期的運行階段。

 

 

 

常量方式(Constant Recipe

We've just learned how Angular splits the life-cycle into configuration phase and run phase and how you can provide configuration to your application via the config function. Since the config function runs in the configuration phase when no services are available, it doesn't have access even to simple value objects created via Value recipe.    
咱們已經學會了如何區分應用程序生命週期中的配置階段和運行階段,如何經過配置方法向您的應用程序提供配置。因爲配置方法運行在配置階段,此時尚無服務可用,所以它不能訪問任何對象,哪怕是經過 Value recipe 建立的 value 對象。

Since simple values, like url prefix, don't have dependencies or configuration, it is often handy to make them available in both the configuration and run phases. This is what the Constant recipe is for.

而簡單的值,好比 url 的前綴,沒有依賴或配置,須要在配置和運行階段皆可以使用。這就是 Constant recipe。

Let's say that our unicornLauncher service can stamp a unicorn with the planet name it's being launched from if this name was provided during the configuration phase. The planet name is application specific and is used also by various controllers during the runtime of the application. We can then define the planet name as a constant like this:

假設 unicornLauncher 服務能夠標出 unicorn 發射自哪顆行星,並且這個行星的名字須要在配置階段提供。同時,星球的名字會由應用程序指定,而且被多個控制器在運行階段使用。

We can then define the planet name as a constant like this:

咱們能夠按照以下方式定義這個星球的名字爲一個常量:

myApp.constant('planetName', 'Greasy Giant');

We could then configure the unicornLauncherProvider like this:

咱們這樣能夠配置 unicornLauncherProvider:

myApp.config(['unicornLauncherProvider', 'planetName',

And since Constant recipe makes the value also available at runtime just like the Value recipe, we can also use it in our controller and template:

因爲在運行階段,Constant recipe 建立的值和 value recipe 同樣,因此咱們也能夠在控制器和模板中使用它:

myApp.controller('DemoController', ["clientId", "planetName", .clientId =.planetName =<html ng-app="myApp"> 
<body ng-controller="DemoController as demo"><br></body> 
</html>

 

 

特殊目的對象(Special Purpose Objects

Earlier we mentioned that we also have special purpose objects that are different from services. These objects extend the framework as plugins and therefore must implement interfaces specified by Angular. These interfaces are Controller, Directive, Filter and Animation.

如上所述,我還有不一樣於 services,用於特殊目的對象。這些擴展做爲框架的插件,所以必須實現 Angular 指定的接口。這些接口是:控制器、指令、過濾器和動畫效果。

The instructions for the injector to create these special objects (with the exception of the Controller objects) use the Factory recipe behind the scenes.

舉例說明注入器建立特殊對象(控制器對象除外)使用 Factory recipe。

Let's take a look at how we would create a very simple component via the directive api that depends on the planetNameconstant we've just defined and displays the planet name, in our case: "Planet Name: Greasy Giant".

讓咱們看一下如何經過指令 api 建立一個很是簡單的組件,取決於咱們剛纔 planetName 定義的常量和行星的名字,在咱們的例子中:「行星名稱:Greasy Giant」(油膩巨人)。

Since the directives are registered via Factory recipe, we can use the same syntax as with factories.

自從經過工廠方法註冊指令以後,咱們就可使用與 factory 相同的語法。

myApp.directive('myPlanet', ['planetName', 'E'($scope, $element) { $element.text('Planet: ' +

We can then use the component like this:

而後,這樣使用組件:

<html ng-app="myApp">
<body>
<my-planet></my-planet>
</body>
</html>

Using Factory recipes you can also define Angular's filters and animations, but the controllers are a bit special. You create a controller as a custom type that declares its dependencies as arguments for its constructor function. This constructor is then registered with a module. Let's take a look at the DemoController, created in one of the early examples:

使用 Factory recipes,你還能夠定義 Angular 的過濾器和動畫效果,可是控制器有些許特殊。建立一個控制器做爲自定義類型,聲明包含做爲其依賴項參數的構造函數。而後註冊這個構造函數到一個模塊。讓咱們看看 DemoController 先前的例子:

myApp.controller('DemoController', ['clientId', .clientId =

The DemoController is instantiated via its constructor every time the app needs an instance of DemoController (in our simple app it's just once). So unlike services, controllers are not singletons. The constructor is called with all the requested services, in our case the clientId service.

DemoController 是根據應用程序的須要,經過其構造函數實例化的(在咱們的簡單應用中只有一次)。與服務不一樣,控制器並非單例的。構造函數被全部請求的服務調用,在咱們的案例中是 clientId service。

 

 

 

結論(Conclusion

To wrap it up, let's summarize the most important points:

歸納上述內容,讓我來總結一下最重要的幾點:

The injector uses recipes to create two types of objects: services and special purpose objects.

注入器經過使用 recipes 來建立兩種類型的對象:服務和特殊目的對象。

There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant.

一共有五種類型的 recipe 用於定義如何建立對象:變量、工廠、服務、供應者和常量。

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

工廠和服務是最經常使用的方式。二者僅有的不一樣是服務方式對於自定義類型對象效果更好,而工廠方式能夠提供 JavaScript 基元和方法。

The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.

供應者方式是核心方式,全部其它方式都是它的語法糖。

Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.

供應者是最複雜的方式類型。除非你正在構建一段須要全局配置的可重用代碼,不然不要使用它。

All special purpose objects except for Controller are defined via Factory recipes.

全部特殊目的對象都經過工廠方式來定義,除了控制器。

Features / Recipe type

Factory

Service

Value

Constant

Provider

can have dependencies              
支持依賴注入

yes

yes

no

no

yes

uses type friendly injection            
使用友好的注入方式

no

yes

yes*

yes*

no

object available in config phase            
配置階段可用

no

no

no

yes

yes**

can create functions/primitives              
能夠建立方法/基元

yes

no

yes

yes

yes

* at the cost of eager initialization by using new operator directly

以使用 new 操做符初始化爲代價。

** the service object is not available during the config phase, but the provider instance is (see the unicornLauncherProviderexample above).

** 服務對象在配置階段不可用,除了供應者實例(參見上面的 unicornLauncherProvider 示例)。

目前已有部分產品支持AngularJS,Wijmo 就是其中之一。它是爲企業應用程序開發而推出的一系列包含HTML5和JavaScript的開發控件集,不管應用程序是移動端、PC端、仍是必需要支持IE6,Wijmo 均能知足需求。

原文連接: https://docs.angularjs.org/guide/providers

相關文章
相關標籤/搜索