[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 { }
[Angular2 Router] CanActivate Route Guard - An Example of An Asynchronous Route Guard的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [Angular2 Router] Guard: CanLoad
'canLoad' guard can decide whether a lazy load module can be loaded or not. @Injectable() export cla ...
- [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 ...
- [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 ...
随机推荐
- 【LeetCode】96 - Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For examp ...
- BITED数学建模七日谈之五:怎样问数学模型问题
下面进入数学建模经验谈第五天:怎样问数学模型问题 写这一篇的目的主要在于帮助大家能更快地发现问题和解决问题,让自己的模型思路有一个比较好的形成过程. 在我们学习数学模型.准备比赛的时候,经常会遇到各种 ...
- android参考
android:使用BaseExpandableListAdapter实现可折叠的列表 Android-ListView实现SectionIndexer SectionIndexer 的使用(联系人分 ...
- Linux配置静态IP
在一块SSD的CentOS配置静态IP 1. 配置静态IP #vi /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE="eth0" ...
- 主机找不到vmnet1和vmnet8
今天跑程序时,突然发现虚拟机ping不通主机了,返过来可行,防火墙什么的都设置好了,仍然不行,后来发现,在网络和共享中心已经看不到vmnet1和vmnet8了,更改适配器设置也只有本地连接和宽带连接, ...
- BitmapData类介绍
今天介绍另外一个比较常用和中高级难度的类:BitmapData 用好这个类,可以说是半支脚踏入了Flash高手的大门···(主要是不是太多的人精通这个··呵呵··)我也可以趁这篇文章的机会好好巩固+学 ...
- 检查 CPU 是否支持二级地址转换 - 摘自网络
Windows 8 Consumer Preview 于2月正式发布,随后 Windows Server 8 Beta 也公布了下载.整体对比,Windows 8 在硬件方面的要求并不高,其最低硬件需 ...
- android 开发必用的开源库
LogReport: https://github.com/wenmingvs/LogReport, 崩溃日志上传框架 wcl-permission-demo:Android 6.0 - 动态权 ...
- Jquery 操作页面中iframe自动跟随窗口大小变化,而页面不出现滚动条,只在iframe内部出滚动条
很多时候大家需要iframe自适应所加载的页面高度而不要iframe滚动条,但是这次我需要的是页面不需要滚动条而iframe要滚动条,且iframe自动跟随窗口大小变化.自适应页面大小.下面是代码,下 ...
- 第三百四十三天 how can I 坚持
今天又莫名其妙的烦起来了,好没劲. 现在还在看电视机<太阳的后裔>,晚上也没怎么吃饭,干吃了两个馒头,老干妈+生洋葱,好凄惨. 上班看了好长时间会,乱七八糟的. 坚决不跳槽,但得坚持自己的 ...