JustDoItTomorrow
3/8/2018 - 6:18 AM

路由守卫:resolve

// 把CrisisDetailComponent改成从ActivatedRoute.data.crisis属性中获取危机详情,这正是我们重新配置路由的恰当时机。 当CrisisDetailComponent要求取得危机详情时,它就已经在那里了。
ngOnInit() {
  this.route.data // 此信息resolve配置的crisis,现在即可使用
    .subscribe((data: { crisis: Crisis }) => {
      this.editName = data.crisis.name;
      this.crisis = data.crisis;
    });
}
{
  path: ':id',
  component: CrisisDetailComponent,
  canDeactivate: [CanDeactivateGuardService],
  // 这里定义了this.route.data的内容,'resolver'会被转换成真正resolve返回的值
  resolve: {
    crisis: CrisisDetailResolver 
  }
},
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import { Injectable }             from '@angular/core';
import { Observable }             from 'rxjs/Observable';
import { Router, Resolve, RouterStateSnapshot,
         ActivatedRouteSnapshot } from '@angular/router';

import { Crisis, CrisisService }  from './crisis.service';

@Injectable()
export class CrisisDetailResolver implements Resolve<Crisis> {
  constructor(private cs: CrisisService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> {
    let id = route.paramMap.get('id');

    return this.cs.getCrisis(id).take(1).map(crisis => {
      if (crisis) {
        return crisis;
      } else { // id not found
        this.router.navigate(['/crisis-center']);
        return null;
      }
    });
  }
}