Reputation: 8491
How can I force navigation to the '/splash' route on page refresh?
If I find myself at '/discover' and I refresh the page it will remain there, however I'd prefer the application to start from the beginning again (/splash).
const appRoutes: Routes = [
{ path: '', redirectTo: '/splash', pathMatch: 'full' },
{ path: 'splash' , component: SplashComponent },
{ path: 'discover' , component: DiscoverComponent },
{ path: 'broadcast' , component: BroadcastComponent },
{ path: 'notifications' , component: NotificationsComponent },
{ path: 'notifications/:key' , component: NotificationComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
I've attempted to place a router.navigate
call within my parent AppComponent's OnInit
& OnDestroy
methods, however it appears to be ignored.
ngOnInit( ) : void {
this.router.navigate(['splash']);
}
I've also attempted to place the navigate call within the OnDestroy
method of the router itself.
Upvotes: 2
Views: 7713
Reputation: 16728
You can do it by subscribing to the first navigation event of the router in your AppComponent
constructor:
import 'rxjs/add/operator/filter';
import { Router, NavigationStart } from '@angular/router';
export class AppComponent {
private subscription: any;
constructor(private router: Router) {
this.subscription = this.router.events
.filter(e => e instanceof NavigationStart && e.id === 1)
.subscribe(e => {
this.redirectToSplash();
});
}
private redirectToSplash() {
this.router.navigate(["splash"]);
this.subscription.unsubscribe();
}
}
Upvotes: 5