2016-11-21 173 views
0

我剛安裝了Angular 2的全新安裝。但是,當我嘗試注入一種名爲TestService到登錄component這樣的:Angularjs依賴注入不起作用

LoginComponent:

import {Component, Inject} from '@angular/core'; 

@Component({ 
    selector: 'app-login', 
    template: ` 
     {{ test.test }} 
    `, 
    styles: [] 
}) 
export class LoginComponent { 
    constructor(@Inject('test') private test){}; 
} 

應用

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 
import { AppComponent } from './app.component'; 
import { LoginComponent } from './login/login.component'; 
import {TestService} from "./test.service"; 

@NgModule({ 
    declarations: [ 
    AppComponent, 
    LoginComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule 
    ], 
    providers: [{provide: 'test', useClass:TestService}], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

TestService的

import { Injectable } from '@angular/core'; 

@Injectable() 
export class TestService { 
    test = 'test'; 
    constructor() { } 
} 

我收到一個錯誤:

error_handler.js:47EXCEPTION: Error in ./AppComponent class AppComponent - inline template:1:25 caused by: Cannot read property 'name' of undefined 

我在做什麼錯?

+0

錯誤信息似乎與您的問題中的代碼無關。你在哪裏以及如何在AppComponent中使用'name'? –

+0

謝謝你在''AppComponent'''上犯了一個錯誤,就像你說的。 – Jamie

回答

3

鑑於您應該使用Elvis Operator。只是爲了確保test財產將要求在test。目前,當初始更改檢測發生時,test.test會嘗試評估視圖上的綁定。由於最初test未定義test.test失敗。

{{ test?.test }} 
+0

AFAIK字符串作爲提供者密鑰是好的。通常使用'OpaqueToken'是一個好主意,但不是強制性的。 –

+0

@GünterZöchbauer感謝你的提升,我完全錯誤的軌道,我現在可以肯定地說。它與綁定評估.. –

+0

聽起來可能,但我仍然缺少信息在'名稱'被訪問,導致'不能讀取屬性'名稱'的問題。如果你的建議是正確的,它將需要'不能讀取屬性'test',但我認爲這只是在問題提供的代碼中不準確。 –