我有一个主页和菜单,当搜索URL不允许用户时,我希望将用户重定向到主页。如果有人能帮忙的话,谢谢。
发布于 2022-02-01 08:37:38
步骤1:首先创建身份验证服务,必须有身份验证服务。所以你需要创建auth.service.ts.
若要创建服务,请执行以下操作:
ng g service auth
步骤2:创建一个角度保护
这将创建实现auth.guard.ts的CanActivate接口。
创建命令:
ng g guard auth
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']); // go to login if not authenticated
return false;
}
return true;
}
}步骤3:使用路由内部的保护,角路由有一个名为canActivate的属性,它接受一个将在路由到特定路由之前检查的保护数组。
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent,
canActivate: [AuthGuard], // visit home only if authenticated
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }https://stackoverflow.com/questions/70937412
复制相似问题