Angular2:如何呈现组件之前加载数据? [英] Angular2: How to load data before rendering the component?

查看:2408
本文介绍了Angular2:如何呈现组件之前加载数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图组件被渲染之前,从我的API加载的事件。目前我使用我的API服务,这是我从组件的ngOnInit函数调用。

我的 EventRegister 组件:

 进口{组件,OnInit的,ElementRef}从angular2 /芯;
从../../services/api.service进口{ApiService};
进口{} EventModel从'../../models/EventModel';
进口{路由器,ROUTER_DIRECTIVES,ROUTER_PROVIDERS,RouteConfig,RouteParams,RouterLink}从'angular2 /路由器;
进口{FORM_PROVIDERS,FORM_DIRECTIVES,控制}从'angular2 /通用';@零件({
    选择:注册,
    templateUrl:/事件/注册
    //商数组在父组件添加
})出口类EventRegister实现的OnInit {
    事件ID:字符串;
    EV:EventModel;    构造函数(私人_apiService:ApiService,
                        params:一个RouteParams){
        this.eventId = params.get('身份证');
    }    fetchEvent(){无效
        this._apiService.get.event(this.eventId)。然后(事件=> {
            this.ev =事件;
            的console.log(事件); //有值
            的console.log(this.ev); //有值
        });
    }    ngOnInit(){
        this.fetchEvent();
        的console.log(this.ev); //没有价值
    }
}

我的 EventRegister 模板

<&注册GT;
    你好这句话始终是可见的,即使`EV property`没有加载尚未
    < D​​IV * ngIf =EV>
        一旦该`EV property`加载我应该是可见的。目前,我从来没有显示。
        <跨度> {{event.id}}< / SPAN>
    < / DIV>
< /注册>

我的API服务

 导入rxjs /接收
从angular2 / HTTP进口{}的Http;
进口{}注射从angular2 /芯;
进口{} EventModel从'../models/EventModel';@Injectable()
出口类ApiService {
    构造函数(私人HTTP:HTTP){}
    得到= {
        事件:(事件ID:字符串):无极< EventModel> = GT; {
            返回this.http.get(API /事件/+事件ID).MAP(响应=> {
                返回response.json(); //有值
            })。承诺();
        }
    }
}

组件获得了 ngOnInit 函数的API调用完成获取数据之前渲染。所以,我从来没有看到在我看来模板中的事件ID。因此,它看起来这是一个异步的问题。我预计 EV EventRegister 组件)的结合做电动车后,一些工作属性设置。遗憾的是它并没有显示 DIV 标记 * ngIf =EV当属性被设置。

问:我使用的好办法?如果不;什么是组件之前加载数据的最好方法是开始呈现?

注意: ngOnInit 办法在此的 angular2教程

编辑:

两种可能的解决方案。首先是沟 fetchEvent ,只使用了 ngOnInit 函数API服务。

  ngOnInit(){
    this._apiService.get.event(this.eventId)。然后(事件=> this.ev =事件);
}

第二个解决方案。就像给出了答案。

  fetchEvent():无极< EventModel> {
    返回this._apiService.get.event(this.eventId);
}ngOnInit(){
    this.fetchEvent(),然后(事件=> this.ev =事件)。
}


解决方案

的console.log(this.ev)终止后,执行这一点。 fetchEvent(); ,这并不意味着 fetchEvent()调用完成,这仅意味着它计划。当的console.log(this.ev)被执行,则调用服务器还没做过,当然还没有返回值。

修改 fetchEvent()返回无极

  fetchEvent(){无效
    返回this._apiService.get.event(this.eventId)。然后(事件=> {
        this.ev =事件;
        的console.log(事件); //有值
        的console.log(this.ev); //有值
    });
 }

变更 ngOnInit()来等待无极完成

  ngOnInit(){
    this.fetchEvent()然后(()=过夜。;
    的console.log(this.ev)); //现在拥有价值;
}

这实际上是不会买你多少你的使用案例。

我的建议:你的包裹整个模板在< D​​IV * ngIf =isDataAvailable> (模板内容)LT; / DIV>

ngOnInit()

  isDataAvailable:布尔= FALSE;ngOnInit(){
    this.fetchEvent()然后(()=过夜。;
    this.isDataAvailable = TRUE); //现在拥有价值;
}

I am trying to load an event from my API before the component gets rendered. Currently I am using my API service which I call from the ngOnInit function of the component.

My EventRegister component:

import {Component, OnInit, ElementRef} from "angular2/core";
import {ApiService} from "../../services/api.service";
import {EventModel} from '../../models/EventModel';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams, RouterLink} from 'angular2/router';
import {FORM_PROVIDERS, FORM_DIRECTIVES, Control} from 'angular2/common';

@Component({
    selector: "register",
    templateUrl: "/events/register"
    // provider array is added in parent component
})

export class EventRegister implements OnInit {
    eventId: string;
    ev: EventModel;

    constructor(private _apiService: ApiService, 
                        params: RouteParams) {
        this.eventId = params.get('id');
    }

    fetchEvent(): void {
        this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
    }

    ngOnInit() {
        this.fetchEvent();
        console.log(this.ev); // Has NO value
    }
}

My EventRegister template

<register>
    Hi this sentence is always visible, even if `ev property` is not loaded yet    
    <div *ngIf="ev">
        I should be visible as soon the `ev property` is loaded. Currently I am never shown.
        <span>{{event.id }}</span>
    </div>
</register>

My API service

import "rxjs/Rx"
import {Http} from "angular2/http";
import {Injectable} from "angular2/core";
import {EventModel} from '../models/EventModel';

@Injectable()
export class ApiService {
    constructor(private http: Http) { }
    get = {
        event: (eventId: string): Promise<EventModel> => {
            return this.http.get("api/events/" + eventId).map(response => {
                return response.json(); // Has a value
            }).toPromise();
        }     
    }     
}

The component gets rendered before the API call in the ngOnInit function is done fetching the data. So I never get to see the event id in my view template. So it looks like this is a ASYNC problem. I expected the binding of the ev (EventRegister component) to do some work after the ev property was set. Sadly it does not show the div marked with *ngIf="ev" when the property gets set.

Question: Am I using a good approach? If not; What is the best way to load data before the component is starting to render?

NOTE: The ngOnInit approach is used in this angular2 tutorial.

EDIT:

Two possible solutions. First was to ditch the fetchEvent and just use the API service in the ngOnInit function.

ngOnInit() {
    this._apiService.get.event(this.eventId).then(event => this.ev = event);
}

Second solution. Like the answer given.

fetchEvent(): Promise<EventModel> {
    return this._apiService.get.event(this.eventId);
}

ngOnInit() {
    this.fetchEvent().then(event => this.ev = event);
}

解决方案

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet return a value.

Change fetchEvent() to return a Promise

 fetchEvent(): void {
    return  this._apiService.get.event(this.eventId).then(event => {
        this.ev = event;
        console.log(event); // Has a value
        console.log(this.ev); // Has a value
    });
 }

change ngOnInit() to wait for the Promise to complete

ngOnInit() {
    this.fetchEvent().then(() =>
    console.log(this.ev)); // Now has value;
}

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

isDataAvailable:boolean = false;

ngOnInit() {
    this.fetchEvent().then(() =>
    this.isDataAvailable = true); // Now has value;
}

这篇关于Angular2:如何呈现组件之前加载数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆