Angular 2: How to conditionally load a Component in a Route asynchronously?

前端 未结 6 637
花落未央
花落未央 2021-01-31 10:39

I\'d like to attach a component to a route asynchronously, given a condition.

The following example, which works (but is asynchronous), loads one compon

6条回答
  •  -上瘾入骨i
    2021-01-31 11:13

    Very good solution could be "Use auth-guard". You can try implementing interfaces CanActivate/CanLoad and put your condition in that class.

    Based on condition, routes gets activated.

    Example:

    import { Injectable }       from '@angular/core';
    import {
      CanActivate,
      ActivatedRouteSnapshot,
      RouterStateSnapshot
    }                           from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { Router } from '@angular/router';
    
    @Injectable()
    export class AuthorizationGuard implements CanActivate {
      constructor() {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): 
           Observable {
        let url: string = state.url;
        return this.canbeLoaded(url);
      }
    
      canbeLoaded(url: string): Observable {
        return Observable.of(true);  //put your condition here
      }
    }
    

提交回复
热议问题