繁体   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