【问题标题】:Angular 6 repeats page in url and child routes are not workingAngular 6 在 url 中重复页面并且子路由不起作用
【发布时间】:2023-03-18 23:52:01
【问题描述】:

当我刷新页面时,页面添加了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

【问题讨论】:

  • 尝试从子数组中删除{path:'',redirectTo:'admin',pathMatch:'full'}
  • 你使用两个模块进行路由吗?
  • 是的,一个在 layout.component.html 中,另一个在 navigation.component.html(dashboard) 中,删除 {path:'',redirectTo:'admin',pathMatch:'full'} 不起作用
  • 共享两个模块ROUTES
  • 考虑打开路由跟踪以在控制台中查看路由器在做什么。您可以在路由配置中使用enableTracing: true 将其打开。此处示例:angular.io/guide/router#configuration

标签: angular angular-ui-router


【解决方案1】:

如果您使用两个模块来定义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']);

【讨论】:

  • 我试过了,它不起作用 bitbucket.org/parikshitparab6477/travel/get/749df89c35b9.zip 这是我的代码
猜你喜欢
  • 2019-02-01
  • 2019-04-05
  • 2021-09-06
  • 2019-07-03
  • 2019-05-12
  • 2011-04-08
  • 1970-01-01
  • 2017-12-12
  • 2017-08-28
相关资源
最近更新 更多