简体   繁体   中英

How do you hide a route in the angular 2 router?

I am using angular 2 with router 3.0.0-rc.1. Consider the following template from the tutorial:

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

The tutorial somewhat unhelpfully adds: "We could hide the link until the user logs in. But that's tricky and difficult to maintain."

I would like to hide the admin link until the user logs in. (It isn't helpful to simply disable the tab and require login as I don't want users that can't use the feature to even see that the tab is there). Is there an easy way to specify that in the routing?

I wouldn't trust just showing/hiding links. Check out canActivate feature. You can specify if given route can be accessed. Fully covered here http://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html .

Showing/hiding link could be done by some authService that would have roles and a directive, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM