我试图实现一个保护,以防止用户导航到登录页面,一旦他们验证了自己。除了登录页面本身,我想对我的应用程序中的每个页面组件使用这个保护。
下面是我正在尝试的代码:
import { Injectable } from '@angular/core';
import { Router, ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree, CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/authentication.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard<T> implements CanActivate, CanDeactivate<T> {
constructor(private router: Router, private auth: AuthenticationService) {
}
canActivate(
_route: ActivatedRouteSnapshot,
_state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.auth.isAuthenticated() || this.router.navigate(['/login']);
}
canDeactivate(
_component: T,
_currentRoute: ActivatedRouteSnapshot,
_currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (nextState && nextState.url.includes('/login')) {
return !this.auth.isAuthenticated();
}
return true;
}
}import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './guards/auth.guard';
import { HomeComponent } from './pages/home/home.component';
import { LoginComponent } from './pages/login/login.component';
const routes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard],
canDeactivate: [AuthGuard]
},
{
path: '**',
redirectTo: 'home',
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [AuthGuard]
})
export class AppRoutingModule { }我还尝试为登录组件实现一个新的canActive保护,它可以工作,但我不太喜欢这种方法。
我看到了一些类似于https://www.concretepage.com/angular-2/angular-candeactivate-guard-example的例子。在这种情况下,使用接口似乎不正确,因为类型记录不支持默认方法实现。我不想重复对每个组件的验证。
为什么我的实现不被调用?我该怎么做呢?
如有任何建议,将不胜感激。
辅助信息:角v14.1.3
发布于 2022-11-17 05:19:36
您有两个injectable装饰在奥斯警卫,请找到下面的堆栈闪电战工作。
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanDeactivate, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/authentication.service';
@Injectable()
// @Injectable({ providedIn: 'root' }) // <-- mistake here
export class AuthGuard implements CanActivate, CanDeactivate<any> {
constructor(private router: Router, private auth: AuthenticationService) {
}https://stackoverflow.com/questions/74468148
复制相似问题