javascript - Angularjs 依赖注入(inject)不起作用

标签 javascript angular dependency-injection

我刚刚全新安装了 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/

相关文章:

Angular 5 子路由

c# - 哪一个是更好的架构/设计方法?

javascript - 如何让 .getAttribute 和 .removeAttribute 匹配 [onclick* ='ga' ]

javascript - 与其他浏览器相比,为什么 IE 中的滚动指标不同?有什么适当的修复方法吗?

angular - Angular 9 的国际电话输入

c# - Azure 函数中的 Autofac InstancePerRequest 范围

c# - Autofac 构造函数按属性注入(inject)

php - 每 5 秒用 AJAX 刷新我的 php 页面

javascript - CSS标签:before with content styling not working unless id provided for elements

angular - 访问 ngFor 指令中的特定 ElementRef