resolve属性里的值会在路由成功前被预先设定好,然后注入到控制器中。
就是等数据都“就位”后,才进行路由(其实也不能叫路由,因为路由是一些列的操作,其中就包括了设置resolve属性等等)。
这样的好处就是页面仅会被渲染一遍。
sheetInfo.resolve.ts
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { SheetService } from '../../services/sheet.service';
@Injectable()
export class SheetInfoResolverService implements Resolve<SongSheet> {
constructor(private sheetServe: SheetService) {}
resolve(route: ActivatedRouteSnapshot): Observable<SongSheet> {
return this.sheetServe.getSongSheetDetail(Number(route.paramMap.get('id')));
}
}
sheetInfo-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [{
path: 'sheetInfo/:id',
component: SheetInfoComponent,
data: {
title: '歌单详情'
},
resolve: {
sheetInfo: SheetInfoResolverService
}
}];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: [SheetInfoResolverService]
})
export class SheetInfoRoutingModule { }
sheetInfo.component.ts
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs/internal/operators';
export class SheetInfoComponent implements OnInit {
constructor(
private route: ActivatedRoute
) {
this.route.data.pipe(map(res => res.sheetInfo)).subscribe(res => {
...
})
}
}