到目前为止,为了区分我必须绕着子级路线浏览的页面,基本上,如果用户登录了,则必须加载MainComponent
,因为其中有顶部栏。
而是当用户转到login
时,不会加载顶部栏。
我希望当用户登录并转到\
时,加载的页面将是\dashboard
,而当他未登录时,他将转到\
加载的页面将是\login
页面。
我尝试使用authguard
,但是每次添加canActivate: [AuthGuard]
时,我的网站都无法正常工作。
我的文件app-routing.module.ts是:
const routes: Routes = [
{
path: '',
component: MainComponent,
children: [
{ path: '', component: DashboardComponent },
{ path: 'missions', component: MissionComponent },
{ path: 'operators', component: OperatorComponent },
{ path: 'materials', component: MaterialComponent },
{ path: 'bins', component: BinComponent },
{ path: 'main', component: MainComponent },
]
},
{ path: 'login', component: LoginComponent },
];
我的auth.guard.ts是:
constructor(
public afAuth: AngularFireAuth,
public userService: UserService,
private router: Router
) {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
this.userService.getCurrentUser()
.then(user => {
//this.router.navigate(['/operator']);
return resolve(false);
}, err => {
return resolve(true);
});
});
}
答案 0 :(得分:1)
尝试一下:
canActivate() {
return this.userService.getCurrentUser()
.pipe(
tap(user => {
if (!user) {
this.router.navigate(['/operator']);
}
}),
);
}
如果返回了用户,则表示该用户已登录,如果未登录,则将其重定向到您要重定向的任何地方。