【问题标题】:switchMap not accepting a function to be executed inside itswitchMap 不接受要在其中执行的函数
【发布时间】:2018-01-01 12:56:11
【问题描述】:

我尝试执行以下搜索:
我想根据第一个id 搜索一些东西,这会返回一个FirebaseListObservable。然后我尝试在ObservableswitchMap 函数内执行代码,因为搜索通常需要更长的时间,否则我的代码将完成,并且将使用lastLoc 的错误值。

我尝试对一系列点运行此程序,因此我在开始时循环遍历一个数组。

这是我的代码:

evaluateRoutes() {
  this.currentTour.travelDistance = 0;
  this.currentTour.travelTime = 0;
  this.currentTour.workTime = 0;
  const locs = this.currentTour.locIds;
  let lastLoc = null;
  locs.forEach(loc => {
    console.log(lastLoc, loc);
    if (lastLoc !== null) {
      console.log('if durch', lastLoc, loc);
      this.afDb.list('routes', {
        query: {
          orderByChild: 'idStart',
          equalTo: loc
        }
      }).switchMap(items => {
        console.log('switchMap starts', lastLoc, loc);
        const filtered = items.filter(item => item.idEnd === lastLoc);
        const route = filtered[0];
        this.currentTour.routeIds.push(route.$key);
        this.currentTour.routes.push({
          idEnd: route.idEnd,
          idStart: route.idStart,
          travelDistance: route.travelDistance,
          travelTime: route.travelTime,
          tsCreated: route.tsCreated,
          userCreated: route.userCreated
        });
        this.currentTour.travelDistance = +0 + this.currentTour.travelDistance + route.travelDistance;
        this.currentTour.travelTime = +0 + this.currentTour.travelTime + route.travelTime;
      }).subscribe();
    }
    lastLoc = loc;
  });
}

我收到以下错误:

Argument of type '(items: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.

【问题讨论】:

  • switchMap 回调函数没有返回任何内容。
  • 我需要返回什么?我假设我不需要返回任何东西,因为我在一个 observable 中。
  • 仅供参考,当我使用 map 而不是 switchMap 时,代码运行良好。
  • 传递给map的函数可以返回任何值——包括undefined——传递给switchMap的函数必须返回一个ObservableInputundefined不 i> 一个有效的ObservableInput
  • 你知道我是如何解决这个问题的吗?这应该不难吧?我在以类似方式使用它的教程中看到。链接显示ObservableInput interface describes all values that are either an SubscribableOrPromise or some kind of collection of values that can be transformed to Observable emitting that values. Every operator that accepts arguments annotated with this interface, can be also used with parameters that are not necessarily RxJS Observables. 我以为我通过了FirebaseListObservable,因此满足了这个标准。

标签: javascript firebase rxjs angularfire2 switchmap


【解决方案1】:

我通过在switchMap 函数的末尾添加以下内容解决了我的问题:

import { Observable } from 'rxjs/Observable';
.switchMap(items => {
    ...
    return Observable.of(route);
  }).subscribe();

【讨论】:

    【解决方案2】:

    当你不需要修改它的流时,你应该使用 Observable 的do 方法。

    【讨论】:

    • do 的问题是它会立即执行,而在这里我需要等待FirebaseListObservable 返回一个值。由于存在依赖关系,do 将返回错误的值。
    猜你喜欢
    • 2021-11-05
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2018-09-26
    • 2021-12-08
    相关资源
    最近更新 更多