刷新另一页时,角路由会重定向到主页

问题描述 投票:0回答:2

在我的应用程序中,用户登录后有一个主页和其他一些页面。问题是,当我进入其他页面之一并且刷新页面时,它再次将我送回家。这是我的Routes

const routes: Routes = [
  {
    path: '', redirectTo: '/home', pathMatch: 'full'
  },
  {
    path: 'login',  component: LoginComponent 
  },{
    path: 'list',  component: ListComponent, canActivate : [AuthGuardService]
  },{
    path: 'home', component: HomeComponent, canActivate : [AuthGuardService]
  },{
    path: 'detail/:id',  component: HomeComponent, canActivate : [AuthGuardService],
  },{
    path: '**', redirectTo: 'login' ,pathMatch: 'full'
  }
];

应用程序组件具有路由器出口

<div [ngClass]="{'container': (isLoggedIn$ | async), 'mt-2': (isLoggedIn$ | async)}" class="h-100">
    <router-outlet></router-outlet>
</div>

所以,我期望什么?首先,如果我是“列表”页面(localhost:4200/list)并且刷新此页面,则应将其保留在该页面中。在那个页面。但是现在它将我重定向到localhost:4200/home。当然,当我单击列表项时,它应该将我发送到localhost:4200/detail/itemId,但它总是将我发送到家里。谢谢

使用AuthGuardService编辑:

export class AuthGuardService implements CanActivate {
  constructor(private route : Router, private store: Store<AppState>) {}

  canActivate() {
    return this.store
      .pipe(
          select(isLoggedIn),
          tap(loggedIn => {
              if (!loggedIn) {
                this.route.navigate(['login']);
              }
          })
      )  
  }
}

我添加登录效果

login$ = createEffect(() =>
        this.actions$
            .pipe(
                ofType(userActions.login),
                tap(action => {
                    localStorage.setItem('userInfo',
                    JSON.stringify(action.user))
                    this.router.navigate(['home']);
                })
            )
    ,{dispatch: false});
angular typescript angular2-routing router
2个回答
0
投票

您可以尝试使用onSameUrlNavigation重新加载到应用模块中吗?

@NgModule({
   imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
   exports: [RouterModule]
})

0
投票

路由的顺序很重要,因为路由器在匹配路由时会使用首个匹配获胜策略,因此,应将更具体的路由置于不那么具体的路由之上。

  • 首先列出具有静态路径的路由
  • 之后是空路径路由,该路由与默认路由匹配。
  • 通配符路由排在最后,因为它匹配每个URL。

仅当没有其他路由首先匹配时,路由器才会选择它。

参考:https://angular.io/guide/router#route-order

所以您如下更改顺序

const routes: Routes = [
  {
    path: 'login',  component: LoginComponent 
  },{
    path: 'list',  component: ListComponent, canActivate : [AuthGuardService]
  },{
    path: 'home', component: HomeComponent, canActivate : [AuthGuardService]
  },{
    path: 'detail/:id',  component: HomeComponent, canActivate :  [AuthGuardService],
  }
  {
    path: '', redirectTo: '/home', pathMatch: 'full'
  },
  ,{
    path: '**', redirectTo: 'login' ,pathMatch: 'full'
  }
];
© www.soinside.com 2019 - 2024. All rights reserved.