【问题标题】:Angular 2 - Lifecycle event after Constructor CalledAngular 2 - 构造函数调用后的生命周期事件
【发布时间】:2017-04-30 23:09:30
【问题描述】:

我正在尝试使用 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 是否正确?

请帮帮我。

提前感谢您的帮助。

【问题讨论】:

  • 为什么你不能添加像'getProfile'这样的基于promise的方法来控制你的组件流?似乎构造函数和初始化函数本质上不是异步的
  • 我想在加载时有数据

标签: angular components angular2-directives angular2-services angular-components


【解决方案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;
    });
  }
}

【讨论】:

    【解决方案2】:

    根据Service documentation,建议在ngOnInit 内调用服务。检查this documentation 的所有生命周期钩子,根据其OnInit documentation,您应该使用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);
            });        
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果您希望数据在加载时可用,则需要进一步研究解析路由中的数据,这可以在包含您的组件的路由加载之前 http 加载并返回有效负载。

      【讨论】:

        猜你喜欢
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-13
        • 2017-03-29
        相关资源
        最近更新 更多