簡體   English   中英

如何將 combineLatest 與訂閱者一起使用

[英]how to use combineLatest with a Subscriber

我想將 combineLatest 與訂閱者一起使用,並且只有在傳遞的 id 與 itemIds 匹配時才通過此方法訂閱。

這是我到目前為止所做的:

export interface Instance {
  onEvent<T = any>(eventName: string): Subscriber<T>;
}

export interface Payload {
  id: string;
  quantity: number;
}

public async getSingletonSubscription(id: string): Promise<Observable<any>>{
  const instance = await this.instance;
  // itemids is an Observable coming from another method. Just did an array for this example
  const itemIds: Array<number> = [1, 2];

  // Subscriber<any>
  const subscriber = instance.onEvent(message);

  const observable = combineLatest(
    subscriber,
    itemIds
  ).pipe(
    filter((payload: any, ids: any) => ids.include(id))
  );

  return observable
}

我目前收到類型錯誤Argument of type 'Subscriber<any>' is not assignable to parameter of type 'ObservableInput<any> | SchedulerLike | ((...values: any[]) => unknown)' Argument of type 'Subscriber<any>' is not assignable to parameter of type 'ObservableInput<any> | SchedulerLike | ((...values: any[]) => unknown)' Argument of type 'Subscriber<any>' is not assignable to parameter of type 'ObservableInput<any> | SchedulerLike | ((...values: any[]) => unknown)'我目前不確定如何解決這種類型的錯誤。

通常我會這樣使用interface.onEvent

this.interface
  .onEvent(message)
  .subscribe((payload: Payload)) => console.log(payload));

但因為 itemIds 也是一個可觀察的。 當我返回一個 observable 時,我想使用 combineLatest 訂閱一次

您的代碼示例中有很多誤傳,但我將嘗試解釋每一個。

基於以下幾點:

this.interface
  .onEvent(message)
  .subscribe((payload: Payload)) => console.log(payload));

this.interface.onEvent()的返回類型是Observable ,而不是Subscriber Subscriber是對Observable具有活動Subscription的東西。

關於你的方法,我會避免混合PromisesObservables 如果您正在使用 RxJS,則將所有內容都設置為Observable會更容易。 由於this.interface.onEvent(message)返回一個Observable ,我們可以保持原樣。

現在為您更新的代碼:

export interface Instance {
  onEvent<T>(eventName: string): Observable<T>;
}

export interface Payload {
  id: string;
  quantity: number;
}

public getSingletonObservable(id: string): Observable<Payload>{
  const instance$ = this.instance.onEvent<Payload>(message);
  // To make this an observable, we need to wrap it inside the `of()` operator.
  const itemIds$ = of([1, 2]);

  const observable$ = combineLatest([
    subscriber,
    itemIds
  ]).pipe(
    filter(([payload, ids]) => ids.include(payload.id)),
    // I'm assuming we want to return the payload if it passes the previous condition.
    map(([payload, ids]) => payload)
  );

  return observable$;
}

我更新了類型,所以我們不使用any類型(在 TypeScript 中應該不惜一切代價避免)。

我還更新了一些變量名稱,因為如果它是可觀察的,通常將$添加到名稱的末尾。

您還忘記聲明id的定義位置,所以我添加了它的引用,它是payload的一個屬性。

使用any作為 function 的返回類型,而不是 Promise。 希望你能得到解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM