刷新另一个页面时,角度路由重定向到主页

Dav*_*ebj 9 router typescript angular2-routing angular

在我的应用程序中,用户登录后有一个主页和一些其他页面。问题是,当我进入其中一个其他页面并刷新该页面时,它会再次将我发送到主页。这是我的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'
  }
];
Run Code Online (Sandbox Code Playgroud)

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

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

那么,我期望什么?首先,如果我在“列表”页面 ( 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']);
              }
          })
      )  
  }
}
Run Code Online (Sandbox Code Playgroud)

我添加了登录效果

login$ = createEffect(() =>
        this.actions$
            .pipe(
                ofType(userActions.login),
                tap(action => {
                    localStorage.setItem('userInfo',
                    JSON.stringify(action.user))
                    this.router.navigate(['home']);
                })
            )
    ,{dispatch: false});
Run Code Online (Sandbox Code Playgroud)

解决方案:

好吧,经过几个小时的调试,我找到了解决方案。基本上我删除了 this.router.navigate(['home']); 在 AuthGuardService 中,一旦用户登录,我就把它放在组件的登录功能上。放置 this.router.navigate(['home']); 每次我刷新页面时,AuthGuardService 都会触发警卫,因此每次它都会在家里重定向我。就是这样。谢谢

小智 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'
  }
];
Run Code Online (Sandbox Code Playgroud)