Angular 2 http获得可观察的两次调用
发布时间:2020-12-17 07:29:32 所属栏目:安全 来源:网络整理
导读:在Angular 2 v2.0.1中,onInit被调用两次. (显然我在做一次调用时也做错了,但现在不是问题) 这是我的Plunker:http://plnkr.co/edit/SqAiY3j7ZDlFc8q3I212?p=preview 这是服务代码: import {Injectable} from '@angular/core';import {Http,Response} from '
在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) {} } ……以及使用它的简单组件. //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钩子内时被调用两次. 我的问题是,为什么从OnInit函数调用两次? 更新:所有答案的解决方案: 这是新的服务方法: getData() { return this.http.get('./src/data.json') .map((res:Response) => res.json() as PageContent[]); } …这是新的组件方法: loadData(){ this._service.getData() .subscribe(data => this.pages = data); }
您的订阅应该放在组件而不是服务中.作为您的组件的原因是订阅从服务返回的数据,稍后您可以根据需要取消订阅或添加更多控制(例如拒绝).更改后代码将如下所示.
在您的组件中: ngOnInit() { this.loadData(); } loadData(){ this._service.getData().subscribe(data => this.pages = data); } 在你的服务: getData() { return this.http.get('./src/data.json') .map((res:Response) => res.json()); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |