When I refresh page the page adds http://localhost:4200/login
-> http://localhost:4200/login/login
and when I add direct path to http://localhost:4200/dashboard
It should redirect to its child route but it is redirecting to http://localhost:4200/dashboard/login
instead.
I have angular structure like this
I have created layout component where I output router <router-outlet></router-outlet>
parent components ie login,request-access,dashboard
and in dashboard i included another <router-outlet></router-outlet>
for the child paths of the router
My Routes for this structure are as follows:
const routes: Routes = [
{path:'',redirectTo:'login',pathMatch:'full'},
{path:'login',component:LoginComponent},
{path:'request-access',component:RequestAccessComponent},
{path:'dashboard',component:NavigationComponent,
children:[
{path:'',redirectTo:'admin',pathMatch:'full'},
{path:'admin',component:AdminLandingComponent},
{path:'user-list',component:UserListComponent},
{path:'new-request',component:NewRequestComponent},
{path:'payments',component:PaymentsComponent}
]
}
];
this problem occurred when I added this code in login.component.ts
to redirect to the dashboard. after removing code having same issue
loginUser(username:string,password:string){
console.log(username,password);
if(username ===""){
this.erroMessage = "Please enter username."
}else if(password === ""){
this.erroMessage = "Please enter password."
}else{
if(username === "admin" && password === "admin"){
localStorage.setItem('isLoggedIn',"true");
localStorage.setItem('name',"admin");
this.router.navigate(['/admin']);
}else{
this.erroMessage = "Wrong username password. Please try again later"
}
}
}
I tried clearing the local storage using localStorage.clear();
but still the problem occurs
refer this image if I am doing something wrong in the folder structure
I have referred to this question and angularjs documentation Angular4 refresh page repeats page in url
If you are using two module to define the ROUTES
, just try to change:
In app.module.ts
RouterModule.forRoot([
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent },
// other ROUTES
{ path: '**', component: Your_page_not_found_component}
])
In app.component.html:
<router-outlet></router-outlet>
In login component:
import { Router } from '@angular/router';
constructor(private router: Router){}
After successful login in that method:
this.router.navigate(['dashboard']);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.