PatrickJS / angular-hmr

:fire: Angular Hot Module Replacement for Hot Module Reloading
https://patrickjs.com
Apache License 2.0
506 stars 45 forks source link

Keep the state when doing the reload #15

Closed joaogarin closed 8 years ago

joaogarin commented 8 years ago

Hello,

I am curious how to use this to keep my component state when doing reload..Right now if I increment lets say a counter component variable how do I keep it when reloading the component. Should I call set on the app.service.ts service?

/*
 * App Component
 * Top Level Component
 */
@Component({
    // The selector is what angular internally uses
    selector: 'wm-app', // <app></app>
    providers: [AppState],
    // The template for our app
    template: `
    <div>
       <h1>{{name}}</h1>
       <input [(ngModel)]="name" />
    </div>
    <br/>
    <div>
       <span>{{counter}}</span>
       <button (click)="incrementCounter()">Increment number</button>
    </div>
    `
})
export class AppComponent implements OnInit {
    name: string;
    counter: number;

    constructor(public appState: AppState) {
        this.name = 'Angular2 Minimal';
        this.counter = 0;
    }

    incrementCounter() {
        this.counter = this.counter + 1;
    }

    ngOnInit() {
        // Our API
        console.log('Initial App State', this.appState.state);
    }
}

Thank you;)

PatrickJS commented 8 years ago

use @HmrState()

import {HmrState} from 'angular2-hmr';

/*
 * App Component
 * Top Level Component
 */
@Component({
    // The selector is what angular internally uses
    selector: 'wm-app', // <app></app>
    providers: [AppState],
    // The template for our app
    template: `
    <div>
       <h1>{{name}}</h1>
       <input [(ngModel)]="name" />
    </div>
    <br/>
    <div>
       <span>{{counter}}</span>
       <button (click)="incrementCounter()">Increment number</button>
    </div>
    `
})
export class AppComponent implements OnInit {
    name: string;
    @HmrState() counter: number;

    constructor(public appState: AppState) {
        this.name = 'Angular2 Minimal';
        this.counter = 0;
    }

    incrementCounter() {
        this.counter = this.counter + 1;
    }

    ngOnInit() {
        // Our API
        console.log('Initial App State', this.appState.state);
    }
}
joaogarin commented 8 years ago

Tks! Works fine. I just had to do

this.appState.set('counter', this.counter);

when incrementing the counter.

Cool tks;)

Mark-McCracken commented 7 years ago

Is this still valid syntax? Can't see that method available in my verison of @angularclass/hmr from npm. Can you suggest a working alternative for angular version 2.4?

FernandoLeandroFernandes commented 6 years ago

Try this for Angular 4: npm install @angularclass/hmr --save

Source: https://github.com/gdi2290/angular-hmr