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. Asp.Net学习进度备忘(第一步:ASP.NET Web Forms)

    书签:“Web Pages”和“MVC”跳过:另外跳过的内容有待跟进 __________________ 学习资源:W3School. _________________ 跳过的内容: 1.ASP. ...

  2. HTML 学习进度备忘

    书签:”HTML 高级教程“及后面的内容尚未学习,另外跳过的内容有待跟进 __________________ 学习资源:W3School. 开始时间:2013.11.20 简述:此网址做为学习教程相 ...

  3. 淘宝的ruby镜像已无人维护,使用ruby-china的RubyGems镜像

    淘宝的镜像已经无人维护了,参考 https://ruby-china.org/topics/29250 https://gems.ruby-china.org/ 使用新的镜像 $ gem source ...

  4. rhel5.5 Oracle10g安装记录

    ---恢复内容开始--- Rhel5.5 Oracle10g安装成功截图如下

  5. Hadoop学习笔记(2)

    Hadoop学习笔记(2) ——解读Hello World 上一章中,我们把hadoop下载.安装.运行起来,最后还执行了一个Hello world程序,看到了结果.现在我们就来解读一下这个Hello ...

  6. [iOS微博项目 - 3.2] - 发送微博

    github: https://github.com/hellovoidworld/HVWWeibo   A.使用微博API发送微博 1.需求 学习发送微博API 发送文字微博 发送带有图片的微博   ...

  7. CSS元素水平居中和垂直居中的方法大全

    水平居方法: 1.最熟悉的是给元素定义一个宽度,然后使用margin: body{ width:960px; margin:0 auto;}这个是当我们的定义元素的宽度时显现的,如果我们不能定义宽度时 ...

  8. js get 传参 汉字 乱码问题

    js encodeURI(encodeURI(searchWord)) java URLDecoder.decode(searchWord,"utf-8")

  9. c++中__declspec用法总结

    “__declspec”是Microsoft c++中专用的关键字,它配合着一些属性可以对标准C++进行扩充.这些属性有:align.allocate.deprecated. dllexport.dl ...

  10. Oracle数据库编程:使用PL/SQL编写触发器

    8.使用PL/SQL编写触发器: 触发器存放在数据缓冲区中.        触发器加序列能够实现自动增长.        在触发器中不能使用connit和rollback.        DML触发器 ...