【问题标题】:How to use rxjs to create an object observable from another observable?如何使用 rxjs 从另一个 observable 创建一个 observable 对象?
【发布时间】:2022-01-01 05:49:10
【问题描述】:

我想在我的服务中公开一个 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)

但是上面的 sn-p 会产生这个错误(对于withLatestFrom 运算符):

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

我做错了什么?我该如何解决这个问题?

【问题讨论】:

  • 你到底想达到什么目的?

标签: angular rxjs rxjs-observables


【解决方案1】:

您已定义 BehaviorSubject 以保存 stringundefined 值。 所以switchMap 中定义的info 数组的第0 个元素可以是stringundefined,因此需要相应地指定类型定义。应该是:

    info: [string | undefined, SomeObject[]]

【讨论】:

    【解决方案2】:

    对于这个用例,您不需要更高阶的 observable 来订阅另一个 observable,而不是使用 switchMap(),为什么不使用 map() 或 filter()?

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多