【问题标题】:How do you hide a route in the angular 2 router?如何在 angular 2 路由器中隐藏路由?
【发布时间】:2016-09-13 19:28:37
【问题描述】:

我在路由器 3.0.0-rc.1 中使用 Angular 2。请考虑本教程中的以下模板:

`
<nav>
    <a routerLink="/crisis-center" routerLinkActive="active"
       [routerLinkActiveOptions]="{ exact: true }">Crisis Center</a>
    <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
    <a routerLink="/crisis-center/admin" routerLinkActive="active">Crisis Admin</a>
</nav>
<router-outlet></router-outlet>
`

教程有些无益地补充说:“我们可以隐藏链接,直到用户登录。但这很棘手且难以维护。”

我想在用户登录之前隐藏管理员链接。(简单地禁用选项卡并要求登录是没有帮助的,因为我不希望无法使用该功能的用户甚至看到选项卡在那里)。有没有一种简单的方法可以在路由中指定?

【问题讨论】:

    标签: javascript angularjs angular angular2-routing


    【解决方案1】:

    我不相信只是显示/隐藏链接。查看 canActivate 功能。您可以指定是否可以访问给定的路线。在这里完全覆盖http://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html

    显示/隐藏链接可以由一些具有角色和指令的 authService 完成,例如

    import { Directive, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';
    
    @Directive({
      selector: '[yourDirectiveSelector]'
    })
    export class YourDirective implements OnInit {
    
      private customAuthService: CustomAuthService;
      private templateRef: TemplateRef<any>;
      private viewContainerRef: ViewContainerRef;
    
    
      constructor(customAuthService: customAuthService, templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) {
        this.customAuthService = customAuthService;
        this.templateRef = templateRef;
        this.viewContainerRef = viewContainerRef;
      }
    
      ngOnInit() {
        if (this.customAuthService.isOk()) {
          this.viewContainerRef.createEmbeddedView(this.templateRef);
        } else {
          this.viewContainerRef.clear();
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      相关资源
      最近更新 更多