[Angular2 Router] CanActivate Route Guard - An Example of An Asynchronous Route Guard

In this tutorial we are going to learn how we can to configure an can activate route guard in the Angular 2 router. We are going to implement the concrete example where a user can only enter a certain route if its authorized to do so. We are also going to give in this tutorial an example of how a route guard can also make asynchronous calls, by returning an observable that will eventually resolve to true or false.

 

hero-can-activate.ts:

复制代码
import {CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from "@angular/router";
import {Observable, Subject} from "rxjs";
import {StarWarsService} from "./heros.service";
import {Injectable} from "@angular/core";
@Injectable()
export class CanHeroActivateDirective implements CanActivate{

  constructor(private sws: StarWarsService){

  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {

    if(this.sws.people){
      const sub = new Subject<boolean>();
      setTimeout( () => {
        const id = route.params['id'];
        const hero = this.sws.people.find( (p) => {

          return Number(p.id) === Number(id);
        });
        sub.next(hero.mass !== "unknown");
        sub.complete();
      });

      return sub;
    }else{
      return true;
    }

  }

}
复制代码

 

heros.service.ts:

复制代码
import {Injectable, Inject} from '@angular/core';
import {STARWARS_BASE_URL} from "../shared/constance.service";
import {Http} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/switchMap";

@Injectable()
export class StarWarsService {

    people:any;

    constructor(@Inject(STARWARS_BASE_URL) private starwarUrl,
      private http: Http
    ) {}

    getPeople(){
      return this.http.get(`${this.starwarUrl}/people`)
        .map( res => res.json())
        .do( res => this.people = res)
    }

    getPersonDetail(id){
      return this.http.get(`${this.starwarUrl}/people/${id}`)
        .map( res => res.json())
        .map( (hero:any) => Object.assign({}, hero, {
          image: `${this.starwarUrl}/${hero.image}`
        }))

    }
}
复制代码

 

heros.routes.ts:

复制代码
import {HerosComponent} from "./heros.component";
import {RouterModule} from "@angular/router";
import {HeroComponent} from "./hero/hero.component";
import {CanHeroDeactivate} from "./heros-can-deactivate.directive";
import {CanHeroActivateDirective} from "./heros-can-activate.directive";
const routes = [
  {path: '', component: HerosComponent},
  {path: ':id', component: HeroComponent, canDeactivate: [CanHeroDeactivate], canActivate: [CanHeroActivateDirective]},
];
export default RouterModule.forChild(routes)
复制代码

 

hero.module.ts:

复制代码
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HerosComponent } from './heros.component';
import herosRoutes from './heros.routes';
import {HeroComponent} from "./hero/hero.component";
import {StarWarsService} from "./heros.service";
import {RouterModule} from "@angular/router";
import {CanHeroDeactivate} from "./heros-can-deactivate.directive";
import {CanHeroActivateDirective} from "./heros-can-activate.directive";

@NgModule({
  imports: [
    CommonModule,
    herosRoutes
  ],
  declarations: [HerosComponent, HeroComponent],
  providers: [StarWarsService, CanHeroDeactivate, CanHeroActivateDirective]
})
export default class HerosModule { }
复制代码

 

Github

posted @   Zhentiw  阅读(2743)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示