【问题标题】:BehaviorSubject from switchMap then getValue is not a function error来自 switchMap 的 BehaviorSubject 然后 getValue 不是函数错误
【发布时间】:2023-04-07 05:34:01
【问题描述】:

这是我的班级 ts 代码

this.product$ = <BehaviorSubject<Product>>this.route.params.switchMap(
  (params): BehaviorSubject<Product> =>
   this.productService.getProduct(params['_id'])
);

这是来自服务的代码

  getProduct(_id: string): BehaviorSubject<Product> {
    const bs = new BehaviorSubject<Product>
                   (ProductService.initializeProduct());
    if (_id !== '0') {
      this.productSub = this.databaseService.getProduct(_id).subscribe(
        product => {
        bs.next(product);
        }
      );
    }
    return bs;
  }

我声明了类型,也声明了类型,但是当我写的时候

console.log(product$.getValue)

我收到此错误:

ERROR TypeError: this.product$.getValue is not a function

谢谢

【问题讨论】:

    标签: angular rxjs typescript-typings behaviorsubject switchmap


    【解决方案1】:

    switchMap 和 RxJS 通常不是这样工作的。运算符返回的 observable 取决于调用运算符的 observable。所说的observable可以实现lift返回一个同类型的observable实例。

    您调用switchMap 的结果将从this.route.params observable 中提取。它不是BehaviorSubject,也没有getValue 方法。

    【讨论】:

    • 你不能在 sn-p 中做你想做的事。你的问题中的代码就是继续。从代码中推断,您似乎正在尝试同步访问某些内容,这是不可能的。
    • 那是正确的,我正在尝试同步获取值,这可以通过 BehaviorSubject 实现,我唯一的问题是我无法从 swichmap 返回 BehavorSubject。我想摆脱 subscribe 中的嵌套代码,享受 switchmap 的优雅。
    • 这是不可能的,因为this.route.params observable 和this.databaseService.getProduct 返回的 observable 几乎肯定不是同步的。您将不得不处理异步性。
    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多