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负载和线路负载包含您的组件之前返回的有效载荷。

相关问题