我对 Angular 和 Web 编程总体来说还很陌生,我正在尝试创建一个类似向导的表单,包括 5 个步骤。我为这 5 个步骤设置了一个路由,我的目标是防止用户通过 url 跳转到另一个步骤。他应该只使用我提供的两个“下一步”和“后退”按钮,并且只能通过这些按钮完成导航。我知道还有一些方法可以在不使用路由的情况下完成此操作,但我认为使用路由是一个很好的做法。
这些是我的路线:
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/1', pathMatch: 'full' },
{ path: '1', component: FormContainer1Component },
{ path: '2', component: FormContainer2Component },
{ path: '3', component: FormContainer3Component },
{ path: '4', component: FormContainer4Component },
{ path: '5', component: FormContainer5Component }
];
最佳答案
要防止用户通过路由访问组件,您可以使用防护。守卫是根据条件返回 true 或 false 值的服务,如果条件成功,用户就可以访问该组件。
这是路由器中的守卫:
{
path: 'cart',
component : CartComponent,
canActivate : [AuthGuard, NoAdminGuard]
}
这是 guard 本身:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../service/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor( private _authService : AuthService,
private _router : Router){}
canActivate () : boolean{
if(this._authService.loggedIn()){
console.log(localStorage.getItem('token'))
return true
} else{
this._router.navigate(['/login'])
return false
}
}
}
您可以使用以下方式创建守卫:
ng generate guard <name>
关于angular - 有没有办法以 Angular 阻止路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57889525/