When browser back button clicked the app redirects to the first url of the app. For example, current route is localhost:3000
then I'm going to home localhost:3000/home
and then to localhost:3000/settings
and when I click on browser back button it redirects me to localhost:3000
instead of localhost:3000/home
.
I'm using angular 14, but when I started building the app angular was of version 13.
This is app.module.ts
:
@NgModule({
declarations: [AppComponent],
imports: [
...
BrowserModule,
AppRoutingModule,
],
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
...
],
bootstrap: [AppComponent]
})
This is app-routing.module.ts
:
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, onSameUrlNavigation: "reload" }),
BrowserAnimationsModule
],
exports: [RouterModule]
})
The routes all look like this:
{
path: "user/profile",
loadChildren: () => import("./user/profile/profile.module").then(m => m.ProfilePageModule),
canActivate: [LoggedGuard],
},
This is the navigation function that used everywhere for navigation:
async go(path: string[], options: NavigationExtras = {}, showLoader: boolean = true) {
if(showLoader === true) {
await this.loader.start();
}
this.router.navigate(path, { replaceUrl: true, ...options});
}
CodePudding user response:
It would be easier if you share a stackblitz project reproducing your problem.
Maybe it's a problem related with the definition of the routes. You need to set the route to default page, in your case is home
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: 'profile',
loadChildren: () => import('./profile/profile.module').then( m => m.ProfilePageModule)
},
];
CodePudding user response:
I have just figured it out. The function go()
in the question has replaceUrl: true
which replaces the url and not saving the url to browser's history, which means that if you click browser back button it work as you want it to work. Set replaceUrl: false
to save the url to browser history and browser back button will work properly.
So this is how the function looks now:
async go(path: string[], options: NavigationExtras = {}, showLoader: boolean = true) {
if(showLoader === true) {
await this.loader.start();
}
this.router.navigate(path, { replaceUrl: false, ...options});
}
Another thing, please try to use <a routerLink="path"></a>
when possible. This way when the user clicks on link with mouse middle button(scroll wheel) the page will be opened in new tab. Buttons doesn't work like this.