【问题标题】:Angular4 Fetch data before navigating Route ResolveAngular4在导航Route Resolve之前获取数据
【发布时间】:2018-11-17 04:28:47
【问题描述】:

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

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

下面是我想要实现的示例,ContactService 有 3 个方法都需要调用 - 我怎样才能在一次调用中返回所有 3 个方法?

任何指针表示赞赏。

Contact-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


}

【问题讨论】:

  • 方法返回什么?可观察的?
  • @martin 是的,他们返回 Observables

标签: angular rxjs angular5 angular4-router


【解决方案1】:

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

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

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

【讨论】:

  • 如果一个或多个服务调用失败会怎样?
  • @AnuradhaGunasekara forkJoin 不会发射任何东西。
【解决方案2】:

Resolve接口定义如下:

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

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

另一种选择是使用 Martin 建议的 RxJS forkJoin,但如果您想准备具有组合结果的结构化对象,请手动执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 2018-07-08
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多