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

[Angular2 Router] CanActivate Route Guard - An Example of An Asynchronous Route Guard的更多相关文章

  1. [Angular2 Router] Resolving route data in Angular 2

    From Article: RESOLVING ROUTE DATA IN ANGULAR 2 Github If you know Anuglar UI router, you must know ...

  2. [Angular2 Router] Auxiliary Routes bit by bit

    Article Github Auxiliary Routes is is little bit hard to understand. Here is demo, link You can see ...

  3. [Angular2 Router] CanDeactivate Route Guard - How To Confirm If The User Wants To Exit A Route

    In this tutorial we are going to learn how we can to configure an exit guard in the Angular 2 Router ...

  4. [Angular2 Router] Exiting an Angular 2 Route - How To Prevent Memory Leaks

    In this tutorial we are going to learn how we can accidentally creating memory leaks in our applicat ...

  5. [Angular2 Router] Optional Route Query Parameters - The queryParams Directive and the Query Parameters Observable

    In this tutorial we are going to learn how to use the Angular 2 router to pass optional query parame ...

  6. [Angular2 Router] Configuring a Home Route and Fallback Route - Learn An Essential Routing Concept

    In this tutorial we are going to learn how to configure the Angular 2 router to cover some commonly ...

  7. [Angular2 Router] Guard: CanLoad

    'canLoad' guard can decide whether a lazy load module can be loaded or not. @Injectable() export cla ...

  8. [Angular2 Router] Load Data Based on Angular 2 Route Params

    You can load resource based on the url using the a combination of ActivatedRouteand Angular 2’s Http ...

  9. [Angular2 Router] Configure Auxiliary Routes in the Angular 2 Router - What is the Difference Towards a Primary Route?

    In this tutorial we are going to learn how we can can configure redirects in the angular 2 router co ...

随机推荐

  1. leetcode:ZigZag Conversion 曲线转换

    Question: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of ...

  2. SQL Server 2008 备份改进版

    1.Add compressing function with 7-Zip 2.With tool win.rar code so you can change it if you want USE ...

  3. nodejs 基本操作

    查看nodejs版本 nodejs -v 升级nodejs node有一个模块叫n(这名字可够短的...),是专门用来管理node.js的版本的.首先安装n模块:npm install -g n 第二 ...

  4. 一个采用python获取股票数据的开源库,相当全,及一些量化投资策略库

    tushare: http://tushare.waditu.com/index.html 为什么是Python? 就跟javascript在web领域无可撼动的地位一样,Python也已经在金融量化 ...

  5. 60分钟内从零起步驾驭Hive实战学习笔记

    本博文的主要内容是: 1. Hive本质解析 2. Hive安装实战 3. 使用Hive操作搜索引擎数据实战 SparkSQL前身是Shark,Shark强烈依赖于Hive.Spark原来没有做SQL ...

  6. 【MySql】在Linux下安装MySql数据库

    [参数环境] 1.Host OS:Win7 64bit 2.VM: VMware 11.1.0 3.Client OS:CentOS 6 4.系统中已安装的openssl版本: openssl-1.0 ...

  7. NetBeans IDE 7.4 Beta版本build JavaFX时生成的可执行jar包执行时找不到依赖的jar包

    现象,执行时抛出java.lang.ClassNotFoundException异常: Executing E:\secondegg\secondegg-reversi\dist\run8022211 ...

  8. KMP算法——Javascript实现

    腾讯和阿里的笔试刚过去了,里面有很多题都很值得玩味的.之前Blog积累的很多东西,还要平时看的书,都有很大的帮助.这个深有体会啊! 例如,腾讯有一道算法题是吃香蕉(好邪恶的赶脚..),一次吃一根或者两 ...

  9. MYSQL数据库性能调优之八:mysql日志

    MySQL日志 主要包含:错误日志.查询日志.慢查询日志.事务日志.二进制日志.中继日志: 使用 SHOW GLOBAL VARIABLES LIKE '%log%';  查询所有日志配置详情: 一. ...

  10. 用jstack工具分析java程序

    最近做项目时遇到了一个问题,我的多个采集线程中,有一个线程经常挂起,线程并没有死掉,但是一直采集不到数据,为了解决这个问题,用到了jstack. 首先查找到java进程的pid,ps -ef|grep ...