Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Find name error coming in angular2

I have a component called 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(); 
   } */

}

In appService i have

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

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

In app.module.ts i am importing the app service

import { appService } from './app.service'; 


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

Now I am getting an error

cannot find name appService in custom Component line number 15

How can I solve this?

like image 741
udaya Avatar asked Jun 13 '17 09:06

udaya


1 Answers

In CustomComponent file import:

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

Then use it in constructor for DI:

constructor(@Inject(appService) private appService) { }

After this make sure you uncomment appService in providers of your module.

imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  RouterModule,
  appService
],
like image 95
ifadey Avatar answered Sep 20 '22 17:09

ifadey