I am new to Angular2. I am trying to call the simple service from my component but when I try to call it I am getting service instance as undefined:
Here is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>
<script>
System.config({
// we want to import modules without writing .js at the end
defaultJSExtensions: true,
// the app will need the following dependencies
map: {
'angular2': 'node_modules/angular2',
'rxjs': 'node_modules/rxjs',
}
});
// and to finish, let's boot the app!
System.import('built/bootstrap');
</script>
</head>
<body>
<app>Loading...</app>
</body>
</html>
DataService
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Hero } from './hero';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DataService{
getData(){
return "Hi I am a service response";
}
}
Appcomponant.ts
import { Component } from 'angular2/core';
import './rxjs-operators';
import { HeroService } from './toh/hero.service';
import { HeroListComponent } from './toh/HeroListComponent';
@Component({
selector: 'app',
templateUrl: 'hero-list.component.html',
providers:[]
})
export class AppComponent implements OnInit{
constructor (private _dataService: DataService) {}
ngOnInit() { this.getData(); }
private getData(){
this._dataService.getData();
}
mode='this is test mode'
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import {HeroComponent} from 'toh/hero-list-component'
import { AppComponent } from './app.component';
import { HeroService } from './toh/hero.service';
import { DataService } from './toh/DataService';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent],
providers:[DataService]
})
export class AppModule {
}
I also tried to add the provider in both appcomponant.ts and app.module.ts but I am getting the error. Please find the image url mention below:
In Appcomponant.ts, you are injecting dataService as a dependency but you have not imported it. You must call
import { DataService } from './toh/DataService'
in order to inject it as a dependency in your constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.