了解Angular2---App的生命周期

本文介绍Angular2中如何使用根组件引导应用程序,并详细解释了组件的初始化过程及生命周期事件,如onInit、onDestroy等,帮助开发者更好地理解和使用Angular2。

bootstrap

Angular2中,一个App需要用它的根组件进行引导

import {Component, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app',
  template: '<h1>Hello {{ name }}</h1>'
})
// Component controllerclass MyApp {
  constructor() {
    this.name = 'Max';
  }
}

bootstrap(MyApp)

你可以把应用程序的代码和配置文件放到这个组件中,并且整个应用程序的组件链将会在它的模板文件中被创建

初始化组件

当一个组件被创建的时候,它的构造器就会生效.我们就是在这个构造器里面初始化组件的状态.但是如果要用到子组件当中的属性或者数据的话,就需要先等待一段时间.(等父组件依赖的子组件被创建之后才能初始化父组件).

这种情况下,我们可以使用setTimeout来解决这个问题.但是在这里,我们推荐你用生命周期事件onInit:

import {Component, bootstrap, onInit} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'street-map',
  template: '<map-window></map-window><map-controls></map-controls>',
  lifecycle: [onInit]
})

// Component controller
class StreetMap {
  constructor() {
    this.name = 'Max';

    setTimeout(() => {
      // Similar to onInit below, but not recommended.
      // Could be useful in a pinch, though.
    });
  }

  setMapWindow(mapWindow) {
    this.mapWindow = mapWindow;
  }

  setMapControls(mapControls) {
    this.mapControls = mapControls;
  }

  onInit() {
    // Properties are resolved and things like
    // this.mapWindow and this.mapControls
    // had a chance to resolve from the
    // two child components <map-window> and <map-controls>
  }}

组件的生命周期

就像onInit,我们可以根据组件的生命周期追踪几个事件

import {..., onInit, onDestroy, onChange, onCheck, onAllChangesDone} from 'angular2/angular2';
// Annotation section
@Component({
  selector: 'street-map',
  template: '<map-window></map-window><map-controls></map-controls>',
  lifecycle: [onInit, onDestroy, onChange, onCheck, onAllChangesDone]
})
// Component controller
class StreetMap {
  onInit() {
    // Properties are resolved and things like
    // this.mapWindow and this.mapControls
    // had a chance to resolve from the
    // two child components <map-window> and <map-controls>
  }
  onDestroy() {
    // Speak now or forever hold your peace
  }
  onCheck() {
    // Called right after our bindings have been checked
  }
  onChange(changes) {
    // Called right after our bindings have been checked but only
    // if one of our bindings has changed.
    //
    // changes is an object of the format:
    // {
    //   'prop': PropertyUpdate
    // }
  }
  onAllChangesDone() {
    // Called right after all of our bindings have been checked
  }}

原文链接

转载于:https://my.oschina.net/boogoogle/blog/538545

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值