[英]Angularjs dependency injection not working
我刚刚安装了Angular 2
的全新安装。 但是,当我尝试将名为TestService
的服务注入这样的登录component
:
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
我究竟做错了什么?
在视图上,您应该使用Elvis Operator
。 只是为了确保test
属性会在test
询问。 当前,当发生初始更改检测时, test.test
尝试评估视图上的绑定。 由于最初的test
是不确定的,因此test.test
失败。
{{ test?.test }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.