2016-09-13 147 views
0

我使用角度2与路由器3.0.0-rc.1。从教程请看下面的模板:如何在角度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> 
` 

教程有点无助地补充说:“我们可以隐藏,直到用户登录的链接但是,这是棘手和难以维持。”

我想隐藏管理链接,直到用户登录(简单地禁用该选项卡并要求登录是没有用的,因为我不希望用户无法使用该功能甚至看不到该标签在那里)。有没有简单的方法来指定路由?

回答

0

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

显示/隐藏链接可以通过一些authService,将有角色和指令来完成,e.g

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(); 
    } 
    } 
}