Angular2:如何在渲染组件之前加载数据?

我正在尝试在呈现组件之前从我的API加载事件。当前,我正在使用从组件的ngOnInit函数调用的API服务。

我的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
    }
}

我的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>

我的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();
        }     
    }     
}

ngOnInit函数中的API调用完成获取数据之前,将渲染组件。因此,我永远都不会在视图模板中看到事件ID。所以看起来这是一个ASYNC问题。我期望evEventRegister组件)的绑定ev在设置属性后会做一些工作。遗憾的是,设置属性时,它不显示div带有标记的*ngIf="ev"

问题:我使用的是好的方法吗?如果不; 在组件开始渲染之前加载数据的最佳方法是什么?

注意:ngOnInit方法在此angular2教程中使用。

编辑:

两种可能的解决方案。首先是抛弃,fetchEvent然后在ngOnInit函数中使用API??服务。

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

第二个解决方案。喜欢给出的答案。

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

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

转载请注明出处:http://www.xhjyjj.com/article/20230526/911543.html