Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在angular2中找不到名称错误_Angular_Angular2 Services - Fatal编程技术网

在angular2中找不到名称错误

在angular2中找不到名称错误,angular,angular2-services,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}}<

我有一个名为
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(); 
   } */

}
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 { }
现在我得到一个错误

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


如何解决此问题?

替换此代码块

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

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

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

}
问题:

您正在调用此函数。_appService.getApp()

  • 您尚未定义appService

  • 没有应用服务的DI


  • 在CustomComponent文件导入中:

    import { Inject } from '@angular/core';  
    
    然后在DI的构造函数中使用它:

    constructor(@Inject(appService) private appService) { }
    
    在此之后,请确保取消对模块提供程序中的appService的注释

    imports: [
      BrowserModule,
      FormsModule,
      HttpModule,
      RouterModule,
      appService
    ],
    

    您对服务的引用发表了评论?有什么特别的原因吗?为什么在ngOnInit中称之为appService?为什么不
    appService
    ?为什么要删除注入服务的构造函数?另一件事是,
    *ngFor
    语句应该出现在
  • 上,而不是我在app.module.ts中添加的独裁者
      @上
      
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule,
        appService
      ],