[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 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[0]);
  }
复制代码

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)'.

posted @   Zhentiw  阅读(1259)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2014-11-17 [ES6] 02. Traceur compiler and Grunt
2014-11-17 [Node.js] Level 6. Socket.io
2014-11-17 [Grunt] Cleaning your build folder with grunt-contrib-clean
2014-11-17 [Grunt] Minifying your output with grunt-uglify
2014-11-17 [Grunt] Concatenating Your Javascript with grunt-contrib-concat
2014-11-17 [Grunt] Development Automation Tasks with Grunt
点击右上角即可分享
微信分享提示