无法找到 angular2 中的名称错误

uda*_*aya 5 angular2-services angular

我有一个组件叫 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(); 
   } */

}
Run Code Online (Sandbox Code Playgroud)

appService我有

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

@Injectable()
export class appService {  
   getApp(): string { 
      return "Hello world"; 
   } 
} 
Run Code Online (Sandbox Code Playgroud)

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 { }
Run Code Online (Sandbox Code Playgroud)

现在我收到一个错误

在自定义组件行号 15 中找不到名称 appService

我该如何解决这个问题?

ifa*_*dey 8

在 CustomComponent 文件导入中:

import { Inject } from '@angular/core';  
Run Code Online (Sandbox Code Playgroud)

然后在 DI 的构造函数中使用它:

constructor(@Inject(appService) private appService) { }
Run Code Online (Sandbox Code Playgroud)

在此之后,请确保在模块的提供者中取消注释 appService。

imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  RouterModule,
  appService
],
Run Code Online (Sandbox Code Playgroud)


Viv*_*shi 0

替换此代码块

export class CustomComponent {
    heroes = ['first','second','third'];
   //heroes;

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

   ngOnInit(): void { 
      this.value = this.appService.getApp(); 
   }

}
Run Code Online (Sandbox Code Playgroud)

问题 :

您正在调用 this._appService.getApp();

  1. 您尚未定义 _appService。

  2. 还没有为 appService 进行 DI。