Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular HMR RC
import { NgZone } from "@angular/core";
import { Router } from "@angular/router";
import { onBeforeLivesync, onAfterLivesync } from "nativescript-angular/platform-common";
import { RouterExtensions } from "nativescript-angular/router";
let cachedUrl: string;
onBeforeLivesync.subscribe(moduleRef => {
console.log("#### onBeforeLivesync");
if (moduleRef) {
const router = <Router>moduleRef.injector.get(Router);
cachedUrl = router.url;
console.log("-------> Caching URL: " + cachedUrl);
}
});
onAfterLivesync.subscribe(({ moduleRef, error }) => {
console.log(`#### onAfterLivesync moduleRef: ${moduleRef} error: ${error}`);
if (moduleRef) {
const router = <RouterExtensions>moduleRef.injector.get(RouterExtensions);
const ngZone = <NgZone>moduleRef.injector.get(NgZone);
if (router && cachedUrl) {
ngZone.run(() => { // <-- should be wrapped in ngZone
router.navigateByUrl(cachedUrl, { animated: false });
});
}
}
});
import { platformNativeScriptDynamic } from "nativescript-angular/platform";
import { AppOptions } from "nativescript-angular/platform-common";
import { AppModule } from "./app.module";
// Optional - attach to livesync hooks and perfrom navigation
import "./livesync-navigation";
let options: AppOptions = {};
if (module['hot']) {
const hmrUpdate = require("nativescript-dev-webpack/hmr").hmrUpdate;
options.hmrOptions = {
moduleTypeFactory: () => AppModule,
livesyncCallback: (platformReboot) => {
console.log("HMR: Sync...")
hmrUpdate();
setTimeout(platformReboot, 0);
},
}
hmrUpdate();
// Path to your app module. You might have to change if your module is in deferent place
module['hot'].accept(["./app.module"]);
}
// Don't forget to pass the options when creating the platform
platformNativeScriptDynamic(options).bootstrapModule(AppModule);
@NathanWalker

This comment has been minimized.

Copy link

@NathanWalker NathanWalker commented Nov 16, 2018

@vakrilov thanks for this! One slight improvement:

onAfterLivesync.subscribe(({ moduleRef, error }) => {
      console.log(`#### onAfterLivesync moduleRef: ${moduleRef} error: ${error}`);
      if (moduleRef) {
          const router = <RouterExtensions>moduleRef.injector.get(RouterExtensions);
          const ngZone = <NgZone>moduleRef.injector.get(NgZone);
          if (router && cachedUrl) {
            ngZone.run(() => { // <--  should be wrapped in ngZone
              router.navigateByUrl(cachedUrl, { animated: false });
            });
          }
      }
  });

Otherwise the navigate may error if not called inside NgZone 👍

@vakrilov

This comment has been minimized.

Copy link
Owner Author

@vakrilov vakrilov commented Nov 19, 2018

Good catch @NathanWalker - just updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment