angular - 在 angular2 中找不到名称错误

标签 angular angular2-services

我有一个名为 customComponent 的组件

import {Component} from '@angular/core';
import { appService } from './app.service'; 
@Component({
  selector: 'custom-root',
  template: `<h1>how</h1>
    <ul *ngFor="let hero of heroes"><li>{{hero}}</li></ul>`,
})
export class CustomComponent {
    heroes = ['first','second','third'];
   //heroes;

   value: string = ""; 
 // constructor(appService: appService) { }  

   /* ngOnInit(): void { 
      this.value = this._appService.getApp(); 
   } */

}

appService我有
import { 
   Injectable 
} from '@angular/core';  

@Injectable()
export class appService {  
   getApp(): string { 
      return "Hello world"; 
   } 
} 

app.module.ts我正在导入应用服务
import { appService } from './app.service'; 


@NgModule({
  declarations: [
    AppComponent,CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule
   // appService
  ],  
  providers: [appService],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在我收到一个错误

cannot find name appService in custom Component line number 15



我该如何解决这个问题?

最佳答案

在 CustomComponent 文件导入中:

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

然后在 DI 的构造函数中使用它:
constructor(@Inject(appService) private appService) { }

在此之后,请确保您在模块的提供者中取消注释 appService。
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  RouterModule,
  appService
],

关于angular - 在 angular2 中找不到名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517752/

相关文章:

angular - 在多个 boostrapped 组件之间共享服务

javascript - 使用 angular-cli 在仅生产环境中包含许可证文件

angular - 无法列出惰性路由 : Unknown module './src/app/app.module#AppModule'

angular - 加载数据后设置 react 形式(异步)-Angular 5

css - Ionic 3 - 改变模态背景的不透明度?

Angular2 注入(inject)的自定义服务未定义

typescript - 我如何对依赖于 RC3 路由器的组件进行单元测试?

javascript - 在 Angular 2.0 的 Heroes 示例中使用实时 API 需要进行哪些更改

angular - Angular2 中的响应拦截器

Angular 2 RC 5 Bootstrap 自定义 HTTP 类 TypeError : Cannot read property 'toString' of null