我需要在angular 5应用程序中实现一个会话。我想写一个ts文件,基本上,这个ts文件验证用户是否登录。每当页面重新加载或URL更改发生时,我都希望每次调用此ts文件。如何实施?
答案 0 :(得分:-1)
使用AuthGuard
。
创建一个auth-guard.service.ts。
import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
canActivate() {
console.log('i am checking to see if you are logged in');
return true;
}
canActivateChild() {
console.log('checking child route access');
return true;
}
}
之后在您的路由文件中:
export const appRoutes: Routes = [
{
path: 'dashboard',
children: [
{
path: '',
canActivate: [AuthGuard],
component: DashboardComponent
},
{
path: 'users',
component: DashboardUsersComponent,
canActivateChild: [AuthGuard],
children: [
{
path: '',
component: DashboardUsersHomeComponent
},
{
path: ':username',
component: DashboardUserDetailsComponent,
canDeactivate: [CanDeactivateGuard]
}
]
}
]
}
];
以下是您的几个参考链接。
https://scotch.io/courses/routing-angular-2-applications/canactivate-and-canactivatechild
https://ryanchenkie.com/angular-authentication-using-route-guards