刷新页面时,页面会添加http://localhost:4200/login
-> http://localhost:4200/login/login
当我将直接路径添加到http://localhost:4200/dashboard
时,它应该重定向到其子路由,但是它重定向到http://localhost:4200/dashboard/login
。
我有这样的角结构
我已经创建了布局组件,我在其中输出路由器<router-outlet></router-outlet>
父组件
即登录,请求访问,仪表板
并且在信息中心中,我还为路由器的子路径添加了另一个<router-outlet></router-outlet>
此结构的我的路线如下:
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}
]
}
];
当我在login.component.ts
中添加此代码以重定向到仪表板时,发生了此问题。删除具有相同问题的代码后
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"
}
}
}
我尝试使用localStorage.clear();
清除本地存储,但是仍然出现问题
我已经提到了这个问题和angularjs文档 Angular4 refresh page repeats page in url
答案 0 :(得分:0)
如果您使用两个模块来定义ROUTES
,只需尝试更改:
在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}
])
在app.component.html中:
<router-outlet></router-outlet>
在登录组件中:
import { Router } from '@angular/router';
constructor(private router: Router){}
使用该方法成功登录后:
this.router.navigate(['dashboard']);