2
我是Angular2的新手。我想從我的組件調用簡單的服務,但是當我嘗試調用它,我得到的服務實例爲未定義:服務越來越undefined角2
這裏是我的代碼:
的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但我我正在得到錯誤。請看以下圖片網址提及:
你好,請嘗試編輯您的文章,使我們可以有錯誤的圖像更好的鏈路。 此外,還缺少幾點幫助您正確使用:與您的@NgModule對應的代碼。 另一個建議是:你應該在一個單獨的文件,而不是將其放入index.html的分離SystemJS配置,但是這是你的。 提示:有兩個問題:一是你的模塊,因爲這些文件都沒有找到,這是最有可能來自失蹤NPM模塊或systemJS配置,未來的第二個最有可能從NgModule –
未申報的服務關於上述問題陳述的任何建議,謝謝Brain編輯代碼:) –