有没有一种方法可以遮挡成角度的路径?

时间:2019-09-11 12:46:21

标签: angular typescript angular-routing

我一般对角度和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 }
];

2 个答案:

答案 0 :(得分:3)

要防止用户通过路由访问组件,可以使用防护措施。防护是根据条件返回真假值的服务,如果条件成功,则用户可以访问组件。

这是路由器中的守护者:

{
  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>

答案 1 :(得分:0)

您可以使用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 }
    ]
});
相关问题