1

我正在尝试将两个 Observable 组合起来,以便为接受两个值的服务调用方法提供很少的值。但在这里我有几个错误

  • '([filter, sort]: [string, string]) => void' 类型的参数不能分配给 '(value: [string, string], index: number) => ObservableInput' 类型的参数。类型“void”不可分配给类型“ObservableInput”。

  • 在控制台中 -

    您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。在 subscribeTo (subscribeTo.js:27) 在 innerSubscribe (innerSubscribe.js:71) 在 SwitchMapSubscriber._innerSub (switchMap.js:44) 在 SwitchMapSubscriber._next (switchMap.js:34) 在 SwitchMapSubscriber.next (Subscriber.js:49 ) 在 CombineLatestSubscriber.notifyNext (combineLatest.js:73) 在 InnerSubscriber._next (InnerSubscriber.js:11) 在 InnerSubscriber.next (Subscriber.js:49) 在 BehaviorSubject._subscribe (BehaviorSubject.js:14) 在 BehaviorSubject._trySubscribe ( Observable.js:42)

  1. 定义 Observables 和 Subjects。

     private openSortQuerySubject: BehaviorSubject<string> = new BehaviorSubject<string>(this.formatSortQuery(this.multiSortMeta));
     public openSortQuery: Observable<string> = this.openSortQuerySubject.asObservable();
    
     private closedSortQuerySubject: BehaviorSubject<string> = new BehaviorSubject<string>(this.formatSortQuery(this.multiSortMeta));
     public closedSortQuery = this.closedSortQuerySubject.asObservable();
    
  2. 结合可观察的。

       const openQueries$ = combineLatest([this.openFilterQuery, this.openSortQuery]);
       const closedQueries$ = combineLatest([this.closedFilterQuery, this.closedSortQuery]);
    
  3. 在服务方法中使用合并值。

openQueries$
      .pipe(
        switchMap(([filter, sort]) => {
          this.alertService
            .listAlerts(filter, sort);
        }),
        tap(v => console.log(v))
      )
      .subscribe((openAlerts) => {
        this.openAlertsCount = openAlerts.length;
        this.openAlerts = this.parseAlerts(openAlerts);
      });

    closedQueries$
      .pipe(
        switchMap(([filter, sort]) => {
          this.alertService
            .listAlerts(filter, sort);
        })
      )
      .subscribe((closedAlerts) => {
        this.closedAlertsCount = closedAlerts.length;
        this.closedAlerts = this.parseAlerts(closedAlerts);
      });
4

1 回答 1

2

你必须在回调中返回一个 observable(或者 RxJS 知道如何变成 observable 的东西)switchMap

不是这个:

switchMap(([filter, sort]) => {
  this.alertService.listAlerts(filter, sort);
})

但是这个(假设listAlerts返回一个可观察的,一个承诺或类似的):

switchMap(([filter, sort]) => {
  return this.alertService.listAlerts(filter, sort);
})
于 2021-05-19T15:49:31.200 回答