【发布时间】:2020-06-23 14:48:10
【问题描述】:
我尝试创建公共路由和安全路由,每个路由都具有不同的 html 结构(安全路由将具有仪表板感觉/外观,而公共路由具有更多营销类型的结构),但路由不起作用。我感觉我有太多 <router-outlets> 但我不是 100% 确定。
我的 AppRoutingModule 如下所示:
const PUBLIC_ROUTES: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent },
{ path: 'request-demo', component: RequestDemoComponent },
{ path: '**', redirectTo: '' }
];
const SECURE_ROUTES: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent, canActivate: [ LoggedInGuard ] },
{ path: 'u',
canActivate: [ LoggedInGuard ],
children: [
{
path: ':id',
component: UserDetailComponent,
resolve: { user: UserDetailResolver },
pathMatch: 'full',
}
]
}
];
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '', component: PublicLayoutComponent, children: PUBLIC_ROUTES },
{ path: '', component: SecureLayoutComponent, children: SECURE_ROUTES }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html 只是 <router-outlet></router-outlet>
public-layout.component.html 是:
<app-header></app-header>
<router-outlet></router-outlet>
和secure-layout.component.html是:
<app-header></app-header>
<router-outlet></router-outlet>
成功登录后,我的登录服务应通过此路由器(使用路由器)将您从公共布局带到安全布局。
this.router.navigate(["/dashboard"]);
但在登录时,这似乎不起作用,因为我仍在“/”而不是仪表板和控制台中,检查元素,<app-public-layout> 是正在显示的内容。
更新了 login.component.ts 登录功能:
login() {
if (this.authService.login(this.loginModel)) {
this.loginModel.email = "";
this.loginModel.password = "";
console.log(
"Welcome back " + this.authService.currentUser.firstName
);
this.router.navigate(["/dashboard"]);
} else {
console.log(
"Email and/or password is incorrect. Please try again."
);
this.loginModel = {
email: "",
password: ""
};
}
}
login function in auth service (using local user array for dev):
login(userEmail: IUserLogin): boolean {
const userExists = this.users.USERS.find(x => x.email === userEmail.email);
if (userExists) {
this.currentUser = userExists;
localStorage.setItem('user', JSON.stringify(userExists));
return true;
} else {
return false;
}
}
登录守卫:
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(protected router: Router, protected auth: AuthService ) {}
canActivate() {
if (localStorage.getItem('access_token')) {
return true;
}
// not logged in so redirect to login page
this.router.navigate(['/']);
return false;
}
}
【问题讨论】:
-
所以你的问题是,当你登录时,登录服务应该重定向到
/dashboard,但它停留在/?即使您在''上有重定向?你能显示LoginService和LoggedInGuard的相关代码吗? -
用认证服务登录功能和登录保护更新了主线程
-
我删除了 LoggedInGuard 以将其排除在外,成功登录后它仍然重定向到 '/' 并且不显示 /dashboard 或仪表板 html 结构
标签: angular