Angular 6-编写用于路由的Resolve类,该类可以返回多个数据集

时间:2018-10-21 16:11:39

标签: angular angular6 angular-routing

我正在在线阅读如何在Angular中使用路由实现解析功能。但是,在每个示例中,我都遇到了仅由一项服务获取特定数据的resolve类。例如:

import { Injectable } from '@angular/core';
import { APIService } from './api.service';

import { Resolve } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve<any> {
  constructor(private apiService: APIService) {}

  resolve() {
    return this.apiService.getItems();
  }

}

在app.routing.ts中:

const routes: Routes = [
{
  path: 'items/:date',
  component: ItemsComponent,
  resolve: { items: APIResolver }
}
]

但是,如果我想多个解决该怎么办?例如:

import { Injectable } from '@angular/core';
import { APIService } from './api.service';

import { Resolve } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve<any> {
  constructor(private apiService: APIService) {}

  resolveItems() {
    return this.apiService.getItems();
  }

 resolveCars() {
    return this.apiService.getCars();
  }

 resolvePeople() {
    return this.apiService.getPeople();
  }

}

如何重构这些在线示例,以便获取不同的解析数据?

如果这个问题听起来有点含糊,我深表歉意。我可以澄清是否需要。

1 个答案:

答案 0 :(得分:2)

不幸的是,这是不可能的。如果要共享逻辑,则可以扩展基类,如下所示:

export abstract class APIResolve<T> implements Resolve<T> {
  constructor(readonly apiService: APIService) {}

  abstract resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T>;
}

并具有多个解析器:

export class APIItemResolve<T> extends APIResolve<T> {
  resolve(): Observable<T> {
    return this.apiService.getItems();
  }
}

export class APIPeopleResolve<T> extends APIResolve<T> {
  resolve(): Observable<T> {
    return this.apiService.getPeople();
  }
}

export class APICarResolve<T> extends APIResolve<T> {
  resolve(): Observable<T> {
    return this.apiService.getItems();
  }
}

并设置如下路线:

const routes: Routes = [{
  path: 'items/:date',
  component: ItemsComponent,
  resolve: { 
    items: APIItemResolve,
    peoples: APIPeopleResolve,
    cars: APICarResolve
  }
}]

另一种方法是进行全局解决,并将您的物品/人员/汽车保存在共享服务中,而不是保存在路线数据中