簡體   English   中英

服務在angular2中變得未定義

[英]Service getting undefined in angular2

我是Angular2的新手。 我試圖從組件中調用簡單服務,但是當我嘗試調用它時,卻得到了未定義的服務實例:

請在下面找到圖像路徑以供參考

這是我的代碼:

的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中添加提供程序,但出現錯誤。 請找到下面提到的圖片網址:

在Appcomponant.ts中,您將dataService作為依賴項注入,但尚未導入它。 你必須打電話

import { DataService } from './toh/DataService'

為了將其作為依賴項注入到您的構造函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM