在Angular 2 v2.0.1中,onInit被调用两次.(显然我在做一次调用时也做错了,但现在不是问题)
这是我的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) {}
}
Run Code Online (Sandbox Code Playgroud)
......以及使用它的简单组件.
//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 {}
Run Code Online (Sandbox Code Playgroud)
免责声明:它是错误的,但是当从构造函数调用服务方法时,您可以看到它被提供一次,但是当它在ngOnInit钩子内时被调用两次.
我的问题是,为什么从OnInit函数调用两次?
更新:所有答案的解决方案:
这是新的服务方法:
getData() {
return this.http.get('./src/data.json')
.map((res:Response) => res.json() as PageContent[]);
}
Run Code Online (Sandbox Code Playgroud)
......这是新的组件方法:
loadData(){
this._service.getData()
.subscribe(data => this.pages = data);
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*y C 12
您subscribe应该放在组件而不是服务中.作为您的组件的原因是订阅从服务返回的数据,稍后您可以根据需要取消订阅或添加更多控制(例如谴责).更改后代码将如下所示.
在您的组件中:
ngOnInit() {
this.loadData();
}
loadData(){
this._service.getData().subscribe(data => this.pages = data);
}
Run Code Online (Sandbox Code Playgroud)
在你的服务:
getData() {
return this.http.get('./src/data.json')
.map((res:Response) => res.json());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15383 次 |
| 最近记录: |