我正在尝试在呈现组件之前从我的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';
在ngOnInit函数中的API调用完成获取数据之前,将渲染组件。因此,我从没在视图模板中看到事件ID。所以看起来这是一个ASYNC问题。我期望ev(EventRegister组件)的绑定ev在设置属性后会做一些工作。遗憾的是,设置属性时,它不显示div带有标记的*ngIf="ev"。
问题:我使用的是好的方法吗?如果不; 在组件开始渲染之前加载数据的最佳方法是什么?
HUWWW
相关分类