我是Angular2的新手。我试图从我的组件调用简单的服务,但当我尝试调用它时,我得到的服务实例为undefined:
这是我的代码:
的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 {
}
我还尝试在appcomponant.ts和app.module.ts中添加提供程序,但是我收到错误。请在下面找到图片网址:
答案 0 :(得分:0)
在Appcomponant.ts中,您将dataService作为依赖项注入,但尚未导入它。你必须致电
import { DataService } from './toh/DataService'
以将其作为依赖项注入构造函数中。