簡體   English   中英

如何使用 rxjs 從另一個可觀察對象創建可觀察的 object?

[英]How to use rxjs to create an object observable from another observable?

我想在我的服務中公開一個 observable,每次為 BehaviorSubject 分配一個值(並在從列表中過濾它之后)時,它都會發出一個值。 示例實現:

export class MyService {

   // Given a list of all object
   private readonly allObjects$: Observable<SomeObject[]>;  
   // An id of a SomeObject instance
   private readonly mySubject = new BehaviorSubject<string|undefined>(undefined);

   // Expose a single instance from the list of all objects.
   public readonly myObject$: Observable<SomeObject|undefined>;   

   constructor() {

     
     this.myObject$ = 

        // Pipe in the object id (i.e.: 123)
        this.mySubject.pipe(

        // Add the list of all objects
        withLatestFrom(this.allObjects$),

        // Filter out the object whose id is 123 from the list of objects. This filtered 
        // object should be the value emitted by myObject$.
        switchMap(
            (info: [string, SomeObject[]]) =>
                info[1].filter(t => t.name === info[0])));
   }
}

用法:

  mySubject.next('123')  
  this.myObject$.subscribe(console.log)  // prints: SomeObject(with id 123)

然而,上面的代碼片段會產生這個錯誤(對於withLatestFrom運算符):

Argument of type 'OperatorFunction<string | undefined, [string | undefined, 
SomeObject[]]>' is not assignable to parameter of type 'OperatorFunction<string | 
undefined, [string, SomeObject[]]>'.

我究竟做錯了什么? 我該如何解決?

您已將BehaviorSubject定義為保存stringundefined值。 因此,在switchMap中定義的info數組的第 0 個元素可以是stringundefined ,因此需要相應地指定類型定義。 它應該是:

    info: [string | undefined, SomeObject[]]

對於這個用例,您不需要更高階的 observable 來訂閱另一個 observable,而不是使用 switchMap(),為什么不使用 map() 或 filter()?

暫無
暫無

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

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