I have a component that:
Loads router-outlet into view
In its constructor: Subscribe to an ngrx Store veriable which is initialized already
ReRoutingComponent.ts
export class ReRoutingComponent implements OnInit {
HOF$:Observable<any>;
HOF:any;
isUHC:boolean;
constructor(
private _store:Store<any>,
private _router:Router,
private _route:ActivatedRoute
) {
this.HOF$ = _store.select(from_costumer.getHOF);
this.HOF$.subscribe((v:any)=> {
this.HOF = v;
this.isUHC = this.HOF['isUHC'];
if(this.isUHC) {
this._router.navigate(['../uscostumer'], {relativeTo: this._route});
}else {
this._router.navigate(['../globalcostumer'], {relativeTo: this._route});
}
});
}
ngOnInit() {
}
}
So the path domain.com/site/providers re-routes to domain.com/site/providers/globalcostumer by default and to domain.com/site/providers/uscostumer if the ngrx variable was assigned.
Im navigating to domain.com/site/providers using a simple [router-link] directive, not via _router.navigate.
The Problem
You can use the ngOnInit
lifecycle hook to do these stuffs and it will be called everytime you route to it.
export class ReRoutingComponent implements OnInit {
HOF$:Observable<any>;
HOF:any;
subscription;
isUHC:boolean;
constructor(
private _store:Store<any>,
private _router:Router,
private _route:ActivatedRoute
) {}
ngOnInit() {
this.HOF$ = _store.select(from_costumer.getHOF);
this.subscription = this.HOF$.subscribe((v:any)=> {
this.HOF = v;
this.isUHC = this.HOF['isUHC'];
if(this.isUHC) {
this._router.navigate(['../uscostumer'], {relativeTo: this._route});
}else {
this._router.navigate(['../globalcostumer'], {relativeTo: this._route});
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}