typescript - 有没有办法在 Angular 中阻止路径?
我对 Angular 和网页编程总体上还比较新,我正在尝试创建一个类似向导的表单,包括 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 }
];
答案#1
为了防止用户通过路由访问某个组件,你可以使用守卫。守卫是作为服务的,它会根据条件返回一个 true 或 false 值,如果条件满足,用户就可以访问该组件。
这是路由器中的防护程序:
{
path: 'cart',
component : CartComponent,
canActivate : [AuthGuard, NoAdminGuard]
}
这就是护卫本身:
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>
答案#2
你可以使用 UrlHandlingStrategy
在你的 app.module 中你可以导入
import { UrlHandlingStrategy, UrlTree} from '@angular/router';
和
export class CustomUrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url: UrlTree) {
....
// your code
}
extract(url: UrlTree) {
return url;
}
merge(url: UrlTree, whole: UrlTree) { return url; }
然后改变你的
@NgModule({
declarations: [ ...],
...
providers: [...
{ provide: UrlHandlingStrategy, useClass: CustomUrlHandlingStrategy }
]
});
