From Article: RESOLVING ROUTE DATA IN ANGULAR 2

Github

If you know Anuglar UI router, you must know resolve function in ui router, which you can load data before template and controller get inited. In Angular2 router, you can also use resovler.

The recommended (personal preferred) way is use class to resolve the data, becasue you can inject servcie, so you can fetch data instead of hard cord data.

There is another way to use DI 'useValue'. Check out the article.

Create a resolver:

// hero-resolve.directive.ts

import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";
import {StarWarsService} from "./heros.service";
import {Injectable} from "@angular/core"; @Injectable()
export class HeroDetailResolver implements Resolve<any> { constructor(private startWarsService: StarWarsService){ } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | any{
const id = route.params['id'];
return this.startWarsService.getPersonDetail(id);
} }

After create the resovler, you can add to the providers:

@NgModule({
imports: [
CommonModule,
herosRoutes
],
declarations: [HerosComponent, HeroComponent],
providers: [StarWarsService, CanHeroDeactivate, CanHeroActivateDirective, HeroDetailResolver]
})

Routers:

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";
import {HeroDetailResolver} from "./hero-resolver.directive";
const routes = [
{path: '', component: HerosComponent},
{
path: ':id',
component: HeroComponent,
canDeactivate: [CanHeroDeactivate],
canActivate: [CanHeroActivateDirective],
resolve: {
hero: HeroDetailResolver
}
},
];
export default RouterModule.forChild(routes)

Here 'hero' will be used to fetch data from router data.

Component:

import {
Component,
OnInit,
OnDestroy,
ViewChild,
} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {StarWarsService} from "../heros.service";
import {Observable, Subscription, BehaviorSubject} from "rxjs"; export interface Hero{
name: string,
image: string
} @Component({
selector: 'app-hero',
templateUrl: 'hero.component.html',
styleUrls: ['hero.component.css']
})
export class HeroComponent implements OnInit, OnDestroy { @ViewChild('inpRef') input; heroId: number;
hero: BehaviorSubject<Hero>;
description: string;
querySub: Subscription;
routeParam: Subscription;
editing: boolean = false; constructor(private route: ActivatedRoute,
private router: Router,
private starwarService: StarWarsService) { } ngOnInit() { /* // Old way to get data from service when component inited
this.hero = new BehaviorSubject({name: 'Loading...', image: ''}); this.route.params
.map((p:any) => {
this.editing = false;
this.heroId = p.id;
return p.id;
})
.switchMap( id => this.starwarService.getPersonDetail(id))
.subscribe( this.hero);*/ // Here using resolver instead of fetch on fly
this.routeParam = this.route.params
.map((p:any) => p.id)
.subscribe( (id) => {
this.editing = false;
this.heroId = id;
});
this.hero = this.route.data
.map((d:any)=> d['hero']);
} ngOnDestroy() {
this.querySub.unsubscribe();
this.routeParam.unsubscribe();
}
}

Child route and access parnet's router resolver's data

  {path: ':url/:id', children: [
{path: '', component: LessonDetailComponent},
{path: 'edit', component: EditLessonComponent}
], resolve: {
lesson: LessonDataResolver
}},

For 'LessonDetailComponent' and 'EditLessonComponent' can both access the resolve data:

    this.route.data
.subscribe(
(res) => {
this.lesson = res['lesson'];
}
)

ONE important note that: If return Observable from resolver, the observable should completed! Otherwise, it doesn't work. So why in the exmaple, it works, because $http.get(), it complete itself.

But if you use AngualrFire2, you fetch data from Firebase like:

  findLessonByUrl(url){
return this.angularFireRef.database.list('lessons', {
query: {
orderByChild: 'url',
equalTo: url
}
})
.filter(r => !!r)
.map(res => res[]);
}

The observable doesn't complete itself, so in the resolver, you need to find a way to make the observable completed.

For example:

import {Resolve, RouterStateSnapshot, ActivatedRouteSnapshot} from "@angular/router";
import {Observable} from "rxjs";
import {CourseService} from "../course.service";
import {Injectable} from "@angular/core"; @Injectable()
export class LessonDataResolver implements Resolve {
constructor(private lessonService: CourseService){ } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
const url = route.params['id'];
return this.lessonService.findLessonByUrl(url).first();
} }

Here it calls .first() to complete the observable. Or you can use '.take(1)'.

[Angular2 Router] Resolving route data in Angular 2的更多相关文章

  1. [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 ...

  2. [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 An ...

  3. [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 ...

  4. Angular2 - Starter - Routes, Route Resolver

    在基于Angualr的SPA中,路由是一个很重要的部分,它帮助我们更方便的实现页面上区域的内容的动态加载,不同tab的切换,同时及时更新浏览器地址栏的URN,使浏览器回退和前进能导航到历史访问的页面. ...

  5. [Angular2 Router] Preload lzay loading modules

    From router v3.1.0, we have preloading system with router. PreloadAllModules After the init module l ...

  6. [Angular2 Router] Setup page title with Router events

    Article import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator ...

  7. [Angular2 Router] Programmatic Router Navigation via the Router API - Relative And Absolute Router Navigation

    In this tutorial we are going to learn how to navigate programmatically (or imperatively) by using t ...

  8. [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 ...

  9. Vue中美元$符号的意思与vue2.0中的$router 和 $route的区别

    vue的实例属性和方法 除了数据属性,Vue 实例还暴露了一些有用的实例属性与方法.它们都有前缀 $,以便与用户定义的属性区分开来.例如: var data = { a: 1 } var vm = n ...

随机推荐

  1. HDU 4696 Answers 水题

    http://acm.hdu.edu.cn/showproblem.php?pid=4696 由题意可知 1<=Ci<=2 而且图上一定有环 那么我们可以得出: 只要存在奇环(即Ci=1) ...

  2. 用Vue+axios写一个实时搜索

    刚刚在学vue,试着写了一个实时搜索文件. 思路:1.input 通过v-model绑定.2.通过watch检测输入结果变化.3根据结果变化从api调用不同的数据. 代码如下: <!DOCTYP ...

  3. 阅读笔记—EL表达式

    表达式语言(EL) 表达式语言是一种在JSP页面中使用的数据访问语言,通过它可以很方便地在JSP页面中访问应用程序数据. 使用EL访问数据 表达式语言的使用形式:              ${exp ...

  4. 最简单的基于FFmpeg的移动端例子:Android 视频转码器

    http://blog.csdn.net/leixiaohua1020/article/details/47056365

  5. UVA 11346 Probability (几何概型, 积分)

    题目链接:option=com_onlinejudge&Itemid=8&page=show_problem&problem=2321">https://uva ...

  6. jquery init 关系

      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/st ...

  7. [LuoguP4892]GodFly的寻宝之旅 状压DP

    链接 基础状压DP,预处理出sum,按照题意模拟即可 复杂度 \(O(n^22^n)\) #include<bits/stdc++.h> #define REP(i,a,b) for(in ...

  8. 10.查看npm安装信息和版本号

    转自:http://www.runoob.com/nodejs/nodejs-express-framework.html 你可以使用以下命令来查看所有全局安装的模块: $ npm list -g ├ ...

  9. 洛谷P3954 成绩【民间数据】

    题目背景 数据已修复 题目描述 牛牛最近学习了C++入门课程,这门课程的总成绩计算方法是: 总成绩=作业成绩×20%+小测成绩×30%+期末考试成绩×50% 牛牛想知道,这门课程自己最终能得到多少分. ...

  10. 如何修复和检测Windows系统漏洞

    本文为<如何给系统打补丁(知识篇)>一文实战文章.   本文出自 "李晨光原创技术博客" 博客,谢绝转载!