2016-11-21 187 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',但我认为这只是在问题提供的代码中不准确。 –