在Angular 2 v2.0.1中,onInit被调用两次. (显然我在做一次调用时也做错了,但现在不是问题)
原文链接:https://www.f2er.com/angularjs/142158.html这是我的Plunker:http://plnkr.co/edit/SqAiY3j7ZDlFc8q3I212?p=preview
这是服务代码:
import {Injectable} from '@angular/core'; import {Http,Response} from '@angular/http'; import {Observable} from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; @Injectable() export class DemoService { constructor(private http:Http) { } // Uses http.get() to load a single JSON file getData() { return this.http.get('./src/data.json') .map((res:Response) => res.json()) .do(data => console.log(data)) .subscribe(data => { return <PageContent[]>data; },error => console.log("there was an error!")); } } export class PageContent { constructor(public _id: string,public tag: string,public title: string,public body?:string,public image?: string) {} }
……以及使用它的简单组件.
//our root app component import {Component,NgModule,OnInit } from '@angular/core' import {BrowserModule} from '@angular/platform-browser' import { DemoService,PageContent } from './service'; import { HttpModule } from '@angular/http'; @Component({ selector: 'my-app',template: ` <div> <h2>Hello {{name}}</h2> </div> <div *ngFor="let page of pages"> {{ page.title }} </div> ` }) export class App implements OnInit { name:string; pages: PageContent[] = []; constructor(private _service: DemoService) { this.name = 'Angular2' this.loadData(); // <-- this is called once } ngOnInit() { //this.loadData(); // <-- this is called twice } loadData(){ this.pages = this._service.getData(); console.log(this.pages); } } @NgModule({ imports: [ BrowserModule,HttpModule ],declarations: [ App ],providers: [DemoService],bootstrap: [ App ] }) export class AppModule {}
免责声明:它是错误的,但是当从构造函数调用服务方法时,您可以看到它被提供一次,但是当它在ngOnInit钩子内时被调用两次.
更新:所有答案的解决方案:
这是新的服务方法:
getData() { return this.http.get('./src/data.json') .map((res:Response) => res.json() as PageContent[]); }
…这是新的组件方法:
loadData(){ this._service.getData() .subscribe(data => this.pages = data); }