我正在学习角5。我正在使用Azure ADAL对用户进行身份验证。
当路径为空时,我将用户路由到登录页。如果用户尚未登录,我们将提供一个登录按钮,单击该按钮后,用户将进入microsoft登录页面。下面是代码。
app-routing.module.ts程序
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full' }
];
@NgModule({
exports: [RouterModule],
imports: [RouterModule.forRoot(routes)]
})
export class AppRoutingModule { }
login.component.ts登录
import { Component, OnInit } from '@angular/core';
import { Adal5Service } from 'adal-angular5';
const config = {
tenant: 'xxxxxxx',
clientId: 'xxxxxx'
}
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor (private service: Adal5Service) {
this.service.init(config);
}
ngOnInit() {
this.service.handleWindowCallback();
if (this.service.userInfo.authenticated) {
window.location.href = "home";
}
}
public isLoggedIn () {
return this.service.userInfo.authenticated;
}
public login () {
this.service.login();
}
}
login.component.html登录
<input type="text" placeholder="CWOPA" class="cwopa-field" />
<button class="login-button" (click)='login()'>Login</button>
但是,当用户键入主屏幕url时,即使用户没有登录,屏幕也会打开。所以我在login.component.ts中添加了一个isLoggedIn()方法,并在home component的on in it方法中调用它。下面是代码
主页.component.ts
import { Component, OnInit } from '@angular/core';
import {LoginComponent} from '../login/login.component'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ LoginComponent ]
})
export class HomeComponent implements OnInit {
private loginComponent: LoginComponent;
constructor(loginComponent: LoginComponent) {
this.loginComponent = loginComponent;
}
ngOnInit() {
if (!this.loginComponent.isLoggedIn()) {
window.location.href = '/login';
}
}
}
同样的情况将在所有组件中重复。
我的问题是,每当添加新组件时,如果isLoggedIn方法不是从组件的on init方法调用的,则视图将在没有身份验证的情况下显示。有没有更好的方法来保护应用程序中的所有视图,而不必在组件的on init方法中编写代码?