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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章