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

NG2: angular2-webpack-starter - what is the purpose of HMR?

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

这个种子使用 HMR 但我不完全明白它的目的是什么。

一开始,我以为HMR是关于动态加载和 在网络应用 运行.

时替换组件

但是自从我把目光投向 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 ));
  }
}

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

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

这里装饰器@HmrState()的目的是什么?

谢谢。

当我第一次看到 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);
  }

}

我们输入一些值,例如'test123' 然后点击按钮。有效。

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

@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 的值。