2016-04-03 63 views
0

參考代碼:角2 DI查詢

https://plnkr.co/edit/j5qPROsWX2mGCQMIigee?p=info

它去是這樣的:

import {Component, Inject, provide} from 'angular2/core'; 
import {Hamburger} from '../services/hamburger'; 

@Component({ 
    selector: 'app', 
    template: `Bun Type1: {{ bunType1 }} 
    <br/> 
    Are these same instances : {{equality}} 
    ` 
}) 
export class App { 
    bunType: string; 
    constructor(@Inject(Hamburger) h1, @Inject(Hamburger) h2) { 
    this.bunType1 = h1.bun.type; 


    if (h1 === h2) { 
     this.equality = 'true'; //this is the outcome 
    } else { 
     this.equality = 'false'; 
    } 

    } 
} 

在App類中,我們注入兩個不同的變量h1和h2。 我打電話給他們不同,因爲我相信angular2框架確實像

h1 = new Hamburger() 
h2 = new Hamburger() 

現在注入兩個不同的對象到應用程序的構造。如果是這種情況,那麼我們如何得到結果(h1 === h2)= true?

回答

-1

因爲您在引導應用程序時指定了Hamburger類的提供程序,所以對應的實例是整個應用程序的單例(實例化一次,然後總是使用此實例)。

bootstrap(AppComponent, [ Hamburger, (...) ]); 

出於這個原因,注射此服務供應商(在Hamburger類)的參數時,你將永遠有相同的實例(即使你注射兩次)。

它不取決於參數名稱(h1和h2),而取決於您使用的標記(在@Inject或類名稱中)。

這是依賴注入(和分層注入器)在Angular2中的工作方式。有關詳細信息,你可以看一下這個問題:

這種行爲例如允許實現共享服務,即共享相同的服務實例與依賴注入幾個組件之間。