0

我正在嘗試使用Angular 2做一個簡單的工作。Angular 2 - 構造函數調用後的生命週期事件

我想在組件的構造函數調用完成後捕獲事件。 我想提出一個網絡調用構造函數像這個 -

import { Component } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { Profile } from '../../dataModel/Profile.ts'; //Data Model 

@Component({ 
    selector: 'profile-list', 
    template: require('./profileList.component.html'), 
    styles: [require('./profileList.component.css')] 
}) 

export class ProfileListComponent 
{ 
    public profiles: Profile[];   //Can be accessed in view 
    public loadingMessage: string = "Loading Data .."; 

    constructor(http: Http) 
    { 
     http.get('/api/Profile/Get?currentPageNo=1&pageSize=20').subscribe(result => 
     { 
      this.profiles = result.json(); 
      console.log(result); 
     }); 
    } 

    ngOnInit() 
    { 
     this.loadingMessage = "No Data Found !!!"; 
    } 
} 

所以,我不知道什麼時候構造函數調用結束。

我想在構造函數調用完成時捕獲事件。

從這2鏈接 -

  1. http://learnangular2.com/lifecycle/

  2. http://learnangular2.com/lifecycle/

我才知道這個 -

export class App implements OnInit{ 
    constructor(){ 
    //called first time before the ngOnInit() 
    } 

    ngOnInit(){ 
    //called after the constructor and called after the first ngOnChanges() 
    } 
} 

所以,在我的constructor呼叫完成後調用onInit是否正確?

請幫幫我。

在此先感謝您的幫助。

+0

爲什麼不能像'getProfile'這樣的基於promise的additinal方法來控制組件流?似乎constrcutors和initalizors在其性質上不是異步的 – VadimB

+0

我想在加載時有數據 –

回答

1

如果您使用路由器呈現定義的組件,這可以成爲您的解決方案嗎? https://angular.io/docs/ts/latest/guide/router.html#!#guards

在初始化組件之前,可以使用路由器功能預取數據。

此刻,任何用戶都可以隨時在應用程序中的任何位置導航。

這並不總是正確的做法。

  • 也許用戶無權導航到目標組件。
  • 也許用戶必須先登錄(認證)。
  • 也許我們應該在顯示目標組件之前獲取一些數據。
  • 我們可能想要在離開組件之前保存未決更改。
  • 我們可能會詢問用戶是否可以放棄掛起的更改而不是保存它們。
import { Injectable }    from '@angular/core'; 
import { Router, Resolve, ActivatedRouteSnapshot } from '@angular/router'; 

@Injectable() 
export class ComponentRouteResolve implements Resolve<ComponentName> { 
    constructor(private router: Router) {} 
    resolve(route: ActivatedRouteSnapshot): Promise<boolean>|boolean { 
    return this.myService().then(data => { 
     return true; 
    }); 
    } 
} 
0

按照Service documentation建議撥打ngOnInit以內的服務。檢查所有的生命週期掛鉤的this documentation,並按照其OnInitdocumentation你應該使用ngOnInit主要有兩個原因:

  1. 建設
  2. 後不久進行復雜的初始化設置組件角設置輸入特性後

所以您的組件應該像如下:

export class ProfileListComponent 
{ 
    public profiles: Profile[];   //Can be accessed in view 
    public loadingMessage: string = "Loading Data .."; 

    constructor(private http: Http) {   
    } 

    ngOnInit() 
    { 
     this.http.get('/api/Profile/Get?currentPageNo=1&pageSize=20').subscribe(result => 
     { 
      this.profiles = result.json(); 
      console.log(result); 
     });   
    } 
} 
0

如果你想要的數據可在負載則需要進一步研究解決的路徑中的數據,從而可以HTTP負載和線路負載包含您的組件之前返回的有效載荷。

相關問題