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 !!!";
    }
}

所以,我不确定何时结束构造函数。

我想在完成构造函数呼叫完成时捕捉事件。

来自此两个链接 -

  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被调用了吗?

请帮助我。

事先感谢您的帮助。

如果您使用路由器渲染定义的组件,这可以成为您的解决方案吗?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;
    });
  }
}

根据服务文档,建议在ngOnInit中调用服务。在此文档中检查所有生命周期挂钩,并根据其OnInit文档使用ngOnInit,其主要原因是:

  1. 施工后不久执行复杂的初始化
  2. 在Angular设置输入属性之后设置组件

因此您的组件应如下:

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);
        });        
    }
}

如果要在加载上可用数据,则需要进一步研究路由中的数据,该数据可以http加载并在包含组件的路由加载之前返回有效载荷。

最新更新