我刚刚全新安装了 Angular 2
。但是,当我尝试将名为 TestService
的服务注入(inject)登录 组件
时,如下所示:
登录组件:
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 { }
测试服务
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
我做错了什么?
最佳答案
在 View 中,您应该使用Elvis Operator
。只是为了确保 test
属性会在 test
上询问。目前,当发生初始更改检测时,test.test
尝试评估 View 上的绑定(bind)。由于最初 test
未定义,test.test
失败。
{{ test?.test }}
关于javascript - Angularjs 依赖注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40719961/