Angular2:如何在渲染组件之前加载数据? - Angular2: How to load data before rendering the component?

问题:

I am trying to load an event from my API before the component gets rendered.我试图在组件呈现之前从我的 API 加载一个事件。 Currently I am using my API service which I call from the ngOnInit function of the component.目前我正在使用我从组件的 ngOnInit 函数调用的 API 服务。

My EventRegister component:我的EventRegister组件:

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我的EventRegister模板

<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我的 API 服务

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.该组件在ngOnInit函数中的 API 调用完成获取数据之前被渲染。 So I never get to see the event id in my view template.所以我永远不会在我的视图模板中看到事件 ID。 So it looks like this is a ASYNC problem.所以看起来这是一个 ASYNC 问题。 I expected the binding of the ev ( EventRegister component) to do some work after the ev property was set.我希望evEventRegister组件)的绑定在ev属性设置后做一些工作。 Sadly it does not show the div marked with *ngIf="ev" when the property gets set.遗憾的是,当属性被设置时,它没有显示标有*ngIf="ev"div

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 .注意:angular2 教程中使用了ngOnInit方法。

EDIT:编辑:

Two possible solutions.两种可能的解决方案。 First was to ditch the fetchEvent and just use the API service in the ngOnInit function.首先是fetchEvent并只使用ngOnInit函数中的 API 服务。

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);
}

解决方案:

参考一: https://en.stackoom.com/question/2PbaT
参考二: https://stackoom.com/question/2PbaT
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章