NG2:angular2-webpack-starter - HMR的目的是什么?

时间:2016-06-28 14:01:53

标签: typescript angular webpack seed

我正在清理我的angular2项目,由于很多原因,我决定从种子开始。 This one

此种子使用HMR,但我并不完全明白其目的是什么。

一开始,我认为HMR是关于动态加载和 在Web应用程序运行时替换组件。

但是,既然我已经把注意力放在了app.service.ts上,我就迷路了。以下是此服务的代码:

import { Injectable } from '@angular/core';
import { HmrState } from 'angular2-hmr';

@Injectable()
export class AppState {
  // @HmrState() is used by HMR to track the state of any object during a hot module replacement
  @HmrState() _state = { };

  constructor() {

  }

  // already return a clone of the current state
  get state() {
    return this._state = this._clone(this._state);
  }
  // never allow mutation
  set state(value) {
    throw new Error('do not mutate the `.state` directly');
  }


  get(prop?: any) {
    // use our state getter for the clone
    const state = this.state;
    return state[prop] || state;
  }

  set(prop: string, value: any) {
    // internally mutate our state
    return this._state[prop] = value;
  }


  _clone(object) {
    // simple object clone
    return JSON.parse(JSON.stringify( object ));
  }
}

我在想服务只是提供一个空间来存储一些数据。毕竟,这只是一个例子。

但这一行让我感到困惑:@HmrState() _state = { };。这项服务是否使用HMR来管理我们可以使用this.appState.set('value', value);(这来自HomeComponent)管理的数据,就像一个小Redux的商店(没有动作,调度程序,blabla)?

装饰者@HmrState()的目的是什么?

感谢。

1 个答案:

答案 0 :(得分:17)

当我第一次看angular2-hmr时,我也很惊讶。我认为它类似于热插拔,但它并不是真的。至少从我使用它时看到的。

看起来无论更改类型如何,它总是重新加载应用程序。但是,它可以恢复交换对象的状态。 @HmrState()的目的是在重新加载应用程序时恢复组件的状态。

让我们来看一个小例子。我们有一个带有输入的表单,该表单与某个组件的属性绑定(ngModelformControl):

@Component({
  template: `
    <input [(ngModel)]="inputValue" />
    <button (click)="click()">Click me</button>
  `
})
export class MyComponent {

  public inputValue: string;

  public click() {
    console.log(this.inputValue);
  }

}

我们输入一些值,例如&#39; test123&#39;然后单击按钮。它有效。

然后我们突然意识到:缺少日志描述。所以我们转到我们的代码并添加它:

@Component({
  template: `
    <input [(ngModel)]="inputValue" />
    <button (click)="click()">Click me</button>
  `
})
export class MyComponent {

  inputValue: string;

  public click() {
    console.log('inputValue:', this.inputValue);
  }

}

然后组件的代码被更改,HMR替换它,我们意识到inputValue已丢失。

要在HMR过程中恢复该值angular2-hmr需要一些有关对象状态的信息,然后才能将其清除。这里@HmrState()发挥作用:它指出应该恢复的状态。换句话说,要使第一个代码段与HMR一起使用,应该完成以下操作:

@Component({
  template: `
    <input [(ngModel)]="state.inputValue" />
    <button (click)="click()">Click me</button>
  `
})
export class MyComponent {

  @HmrState() public state = {
    inputValue: ''
  }

  public click() {
    console.log(this.state.inputValue);
  }

}

HMR处理器现在知道状态,它可以使用状态来恢复我们的价值。现在我们将组件代码更改为:

@Component({
  template: `
    <input [(ngModel)]="state.inputValue" />
    <button (click)="click()">Click me</button>
  `
})
export class MyComponent {

  @HmrState() public state = {
    inputValue: ''
  }

  public click() {
    console.log('inputValue:', this.state.inputValue);
  }

}

它神奇地重新加载我们的应用程序,并保留inputValue的值。