[Angular2 Router] Resolving route data in Angular 2
From Article: RESOLVING ROUTE DATA IN ANGULAR 2
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的更多相关文章
- [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] 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 ...
- [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 - Starter - Routes, Route Resolver
在基于Angualr的SPA中,路由是一个很重要的部分,它帮助我们更方便的实现页面上区域的内容的动态加载,不同tab的切换,同时及时更新浏览器地址栏的URN,使浏览器回退和前进能导航到历史访问的页面. ...
- [Angular2 Router] Preload lzay loading modules
From router v3.1.0, we have preloading system with router. PreloadAllModules After the init module l ...
- [Angular2 Router] Setup page title with Router events
Article import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator ...
- [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 ...
- [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 ...
- Vue中美元$符号的意思与vue2.0中的$router 和 $route的区别
vue的实例属性和方法 除了数据属性,Vue 实例还暴露了一些有用的实例属性与方法.它们都有前缀 $,以便与用户定义的属性区分开来.例如: var data = { a: 1 } var vm = n ...
随机推荐
- Mysql学习总结(13)——使用JDBC处理MySQL大数据
一.基本概念 大数据也称之为LOB(Large Objects),LOB又分为:clob和blob,clob用于存储大文本,blob用于存储二进制数据,例如图像.声音.二进制文等. 在实际开发中,有时 ...
- JNDI学习总结(3)——Tomcat下使用C3P0配置JNDI数据源
一.C3P0下载 C3P0下载地址:http://sourceforge.net/projects/c3p0/files/?source=navbar 下载完成之后得到一个压缩包. 二.使用C3P0配 ...
- 洛谷 P3505 [POI2010]TEL-Teleportation
P3505 [POI2010]TEL-Teleportation 题目描述 King Byteasar is the ruler of the whole solar system that cont ...
- AngularJS渲染性能分析
作者:Jiang, Jilin AngularJS中,通过数据绑定.能够十分方便的构建页面.可是当面对复杂的循环嵌套结构时,渲染会遇到性能瓶颈.今天,我们将通过一些列实验,来測试AngularJS的渲 ...
- actionbar-去掉背景的阴影
今天发现一个问题,就是actionbar跟界面的交界处,会有一个阴影,通过调查发现,这个阴影是actionbar的.然后通过在网上找资料,完美解决了问题.解决方法如下 1.在这个actionbar所在 ...
- php课程 12-42 php中类的关键字有哪些
php课程 12-42 php中类的关键字有哪些 一.总结 一句话总结:const.final.static 1.类常量-const2.最终版本-final3.静态成员-static 1.php中类常 ...
- spring定时器完整
介绍:在开发中,我们经常需要一些周期性就进行某一项操作.这时候我们就要去设置个定时器,Java中最方便.最高效的实现方式是用java.util.Timer工具类,再通过调度java.util.Time ...
- CentOS 7 网络配置、远程访问
网络配置(配置固定IP访问) 相关命令 ip add 查看网卡状态 ifup eth0 打开端口eth0 ifdown eth0 关闭端口eth0 dhclient 自动获取IP mii-tool e ...
- Spider_req
requests模块 安装(用管理员身份去打开Anaconda Prompt) conda install requests python -m pip install requests # 以管理员 ...
- ajax中的POST和GET传值
ajax中的POST和GET传值 转自:http://www.cnblogs.com/jtome/archive/2008/12/04/1347864.html Ajax中我们经常用到get和post ...