Skip to content

Instantly share code, notes, and snippets.

@sasxa
Last active July 25, 2018 17:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sasxa/c4cc7ba2e203c7d91106 to your computer and use it in GitHub Desktop.
Save sasxa/c4cc7ba2e203c7d91106 to your computer and use it in GitHub Desktop.
Angular2 Redirection using @ngrx/store
export class _BaseRoute {
public store: Store<any> = getSingleton(Store);
public title: string;
constructor() { }
routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
this.store.dispatch({ type: "UPDATE_ROUTE", payload: { next, prev } });
this.store.dispatch({ type: "UPDATE_UI", payload: { title: this.title } });
}
static canActivate(condition: Promise<boolean> | boolean, next: ComponentInstruction, prev: ComponentInstruction) {
let store: any = getSingleton(Store);
let action = { type: "UPDATE_ROUTE", payload: { next, prev, redirect: ["/Root"] } };
if (prev !== null)
return condition;
if (condition === false) {
store.dispatch(action);
return condition;
} else if (condition && condition.hasOwnProperty("catch")) {
return (<Promise<any>>condition).catch(() => store.dispatch(action));
}
}
}
@CanActivate((next, prev) => {
return _BaseRoute.canActivate(true, next, prev );
})
export class ChildRoute extends _BaseRoute {
constructor(public store: Store<any>) {
super();
}
}
import {Injector} from 'angular2/core'
let appInjectorRef: Injector;
export const appInjector = (injector?: Injector) => {
if (injector)
appInjectorRef = injector;
return appInjectorRef;
}
export function getSingleton(token: any) {
let injector: Injector = appInjector();
return injector.get(token);
}
// bootstrap(....).then((appRef: ComponentRef) => appInjector(appRef.injector))
export class RootRoute {
constructor(
public store: Store<any>,
private _location: Location,
private _router: Router
) {
// router handler
this.store.select('router')
.subscribe((router: any) => {
if (router.redirect) {
if (this._location.path() !== this._router.generate(router.redirect).urlPath) {
this._router.navigate(router.redirect);
} else {
let router = this.store.value.router;
let payload = { next: router.next, prev: router.prev };
// remove redirect instructions from the state
this.store.dispatch({ type: "UPDATE_ROUTE", payload });
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment