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



在我的应用程序中,用户登录后我有一个主页和一些其他页面。问题是,当我在其中一个其他页面中刷新页面时,它会再次将我送回家。这是我的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});

解决方案:

经过几个小时的调试,我找到了解决方案。基本上我删除了这个.router.navigation(['home'](;在AuthGuardService中,用户一登录,我就把它放在组件的登录功能上;在AuthGuardService中,每次我刷新页面时都会触发防护,所以每次它在家重定向我时都会启动防护。就是这样。谢谢

路由的顺序很重要,因为路由器在匹配路由时使用先匹配后获胜的策略,所以更具体的路由应该放在不太具体的路由之上。

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

只有在没有其他路由首先匹配的情况下,路由器才会选择它。

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

所以你改变订单如下

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'
}
];

我看到你解决了你的问题,但想报告发生在我身上的事情,因为它吞噬了我几天的时间。在我的案例中,我们希望在一个新的选项卡中打开一条特定的路线,这与其他路线不同。

<a *ngIf=link.externalRoute href={{link.route}} target="_blank">

它不断打开主页上的新标签。我检查了代码中的路由、身份验证、身份验证保护和手动导航,但找不到任何内容。

原来我的路线名称是错误的。我有"目标路线">,但应该有'#/target route'!丢失的哈希符号使路由无效,因此它将回退到默认路由。

当然,只有当你碰巧在Angular路由中使用哈希时,这才有帮助,但也许有一天这会对某人有所帮助。

最新更新