Angular4 在导航路由解析之前获取数据

Angular4 Fetch data before navigating Route Resolve

我正在尝试使用 Angular 路由解析在路由激活之前获取组件数据。

我看到的所有示例都在服务中调用一个方法,return,我在服务中有 5 个不同的方法需要调用 b4 组件被激活。

下面是我试图实现的示例,ContactService 有 3 个方法都需要调用 - 如何 return 一次调用所有 3 个方法?

感谢任何指点。

联系-Resolver.ts - 下面

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ContactsService } from './contacts.service';

@Injectable()
export class ContactResolve implements Resolve<Contact>
{

  constructor(private contactsService: ContactsService) {}

  resolve(route: ActivatedRouteSnapshot)
  {
    return this.contactsService.getContact(route.paramMap.get('id')); //method in Service
  }

//  return this.contactsService.getCities(); //Another method in Service that also needs to be called

 // return this.contactsService.getAllParts(); //Another method in Service that also needs to be called


}

您可以只使用 forkJoin,它将等待所有源 Observable 完成:

resolve(route: ActivatedRouteSnapshot) {
  return Observable.forkJoin(
    this.contactsService.getContact(route.paramMap.get('id')),
    this.contactsService.getCities(),
    this.contactsService.getAllParts()
  );
}

所有结果将在包含 3 个项目的单个数组中提供。

Resolve接口定义如下:

interface Resolve<T> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
}

方法 resolve 可以 return ObservablePromise,或者只是某种类型的对象。在您的情况下,您应该订阅 ContactService 内的联系人、城市和部分。当那里接收到所有三个数据时,将它们组合在一个对象中,并在单独的方法中 return ,例如getCombinedData,您可以从解析器调用它。

另一种选择是使用 RxJS forkJoin,正如 martin 所建议的那样,但是如果您想准备一个具有组合结果的结构化对象,请手动进行。