[英]Angular routing to always go to login page if user is not logged in
我想设置我的Angular路线来执行以下操作:
如果用户未登录,则网站( http:// localhost:4200 )的登录页面和任何其他路由都应进入LoginComponent。
如果用户登录,则网站的登录页面( http:// localhost:4200 )和所有不匹配的路由都应转到DashboardComponent。如果路由匹配,则应转到正确的Component。
所有匹配的路由都应由AuthGuard保护,后者检查用户是否已登录。如果用户未登录,则应以LoginComponent结尾。 (AuthGuard处理此重定向)。
我面临的一个主要问题是我不希望LoginComponent成为我的app.component结构的一部分,该结构中具有路由器出口(即,页眉,页脚,侧边栏)。 相反,我只希望登录页面仅显示LoginComponent.html中的内容。
这是我目前的路线:
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full', canActivate: [AuthGuard] },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'projects', component: ProjectListComponent, canActivate: [AuthGuard] },
{ path: 'projects/new', component: ProjectDetailComponent, canActivate: [AuthGuard] },
{ path: 'projects/edit/:id', component: ProjectDetailComponent, canActivate: [AuthGuard] }
];
AuthGuard方法的一个问题是您可以通过AuthGuard,然后您在后端的会话将过期。 但是,除非更改路线,否则不会被踢出局。
为了克服这一点,人们通常使用HTTP拦截器。 如果任何HTTP请求通过重定向到登录页面以“ 401未经授权”响应,则拦截器基本上会将您踢出(除非您已经在登录页面上)。
这样,如果用户不更改路线并开始单击,并且后端响应401,则即使他们不更改路线,也会被踢出用户。
尽管这不能回答您的问题,但它具有很高的相关性。
希望能帮助到你。
**In app.routing.ts**
routes: Routes = [
{
path: '',
component: LoginComponent,
children: [
{
path: 'login',
canActivate: [AuthGuard]
}
]
},
{
path: '', component: WebLayoutComponent,canActivate: [AuthGuard],
children: [
{ path: '',redirectTo: 'dashboard', component: dashboardComponent, canActivate: [AuthGuard] },
{ path: 'dashboard', component: dashboardComponent,canActivate: [AuthGuard]},
{ path: 'matchedroute1', component: matchedRouteComponent, canActivate: [AuthGuard]},
{ path: 'matchedroute2', component: matchedRouteComponent, canActivate: [AuthGuard]}
]
}
]
**In auth.guard.ts**
import { Router, ActivatedRoute } from '@angular/router';
import { routes } from '../app.routing';
@Injectable()
export class AuthGuard {
constructor(private router: Router,private activatedRoute: ActivatedRoute) {
}
canActivate(routeerstate?: any) {
let url = routeerstate._routerState.url; // this url is unactivated route which the user is trying to enter;
let validRoutes = routes;
url = url.replace(/\//g,"");
const isRouteValid = validRoutes.findIndex((item) => item.path === url) > -1 ? true : false;
if(isRouteValid){
if(this.isLoggedIn()) {
if(url === 'login'){
this.router.navigate(['dashboard']);
} else {
return true;
}
} else {
this.router.navigate(['login']);
}
} else {
if(this.isLoggedIn()) { // not valid route and logged In
this.router.navigate(['dashboard']);
}
}
}
isLoggedIn() {
//write your authentication and authorization code and return true or false
}
}
**In app.component.html**
<router-outlet></router-outlet>
**In webLayout.component.html**
<div class= "container">
<app-header></app-header>
<app-ad></app-ad>
</div>
<router-outlet ></router-outlet>
<footer-container></footer-container>
您可以像在应用程序中一样使用两个不同的布局组件。
const routes: Routes = [
{
path: '',
component: HomeLayoutComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
loadChildren: './view/dashboard/dashboard.module#DashboardModule'
},
...
]
},
{
path: '',
component: LoginLayoutComponent,
children: [
{
path: 'login',
loadChildren: './view/login/login.module#LoginModule'
}
]
}
];
这样,您可以在LoginLayoutComponent中隐藏应用程序标题和侧边栏(如果存在),但将其保留在HomeLayoutComponent中。
然后,在AuthGuard中,应检查用户是否已登录。如果尚未登录,则
this.router.navigate(['/login']);
这应该够了吧。
应用程式路线
const approutes : Routes = [
{path:"",component:LoginComponent},
{path:"dashboard",component:DashboardComponent},
];
app.component.ts
import { Component, Input } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'login',
template: `<h1>Hello {{name}}!</h1><a [routerLink] = "['/dashboard']" class="hvr-ripple-in">Login</a>`,
styles: [`h1 { font-family: Lato; }`]
})
export class LoginComponent {
name:string = "Login here implement your login action !"
constructor(private _route:Router) {
}
}
app.component.html
<router-outlet></router-outlet>
navbar.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-navbar',
template: `<h1>{{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class NavbarComponent {
name:string = "Navbar content"
}
footer.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-footer',
template: `<h1>{{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class FooterComponent {
name:string = "Footer content"
}
template.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-template',
template: `<my-navbar></my-navbar><ng-content></ng-content><my-footer></my-footer>`,
styles: [`h1 { font-family: Lato; }`]
})
export class TemplateComponent {
}
dashboard.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'dashboard',
template: `<my-template><h1>Hello {{name}}!</h1></my-template>`,
styles: [`h1 { font-family: Lato; }`]
})
export class DashboardComponent {
name:string = "Dashboard content";
}
因此,如果路由路径为空,则使用单独的布局调用登录组件。 对于仪表板,由于其被包装在模板组件内部,因此被称为单独的布局。 通过这种方式,您可以获取用于登录组件的干净模板。 您还可以在路由器中实现CanActivate功能,以限制用户无需登录即可访问页面。
看看我提供的这个样本供您参考。 https://stackblitz.com/edit/angular-x4jgxs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.