将多个观察者值作为方法参数

发布于 2025-02-11 18:47:37 字数 514 浏览 2 评论 0原文

我正在尝试执行以下操作:

this.httpService.createSomething(
    this.userObserver.getFullName().subscribe(),
    this.userObserver.getPhoneNumber().subscribe(),
    this.userObserver.getEmailAddress().subscribe(),
).subscribe(() => console.log('Well done'));

以上是不起作用的,但这是我可以给出的最好的例子,以描述我想实现的目标,

我可以订阅每种UserObserver方法并将输出值分配给组件属性并将组件属性值传递到createSomething()方法中,但这似乎很混乱,

在一个角模板中,我可以做(this.userobserver.getfullname()| async)查看它的内容是很高兴的。输出值,我想了解其中的内部方法参数

I'm trying to do something like the following:

this.httpService.createSomething(
    this.userObserver.getFullName().subscribe(),
    this.userObserver.getPhoneNumber().subscribe(),
    this.userObserver.getEmailAddress().subscribe(),
).subscribe(() => console.log('Well done'));

The above will not work but it was the best example I could give to describe what i'm trying to achieve

I could subscribe to each of the userObserver methods and assign the output value to a component property and pass the component property values into the createSomething() method but that seems very messy

It's nice that in an Angular template I can do (this.userObserver.getFullName()|async) to view it's output value and i'd like to that inside method parameters

Is that at all possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

城歌 2025-02-18 18:47:37

好吧,有不同的方法可以解决问题。一种方法是使用zipwith订阅可观察到的源的管道操作员,并将其与任何数量的可观察结果输入的值结合使用。 zipwith操作员是RXJS 8的替代zip运算符。您可以做类似的事情:

import { zipWith } from 'rxjs';

private createResult() {
   this.userObservable.getFullName().pipe(
      zipWith(
        this.userObservable.getPhoneNumber(),
        this.userObservable.getEmailAddress()
      ),
      map(([fullName, phoneNumber, emailAddress]) => this.httpService.createSomething(fullName, phoneNumber, emailAddress))
    ).subscribe((result) => console.log(result))
  }

该方法的好处是,您没有将多个订阅彼此嵌套,这可能会导致意想不到的副作用。

well there are different ways of approaching the problem. One way would be to use the zipWith pipe operator that subscribes to a source observable and combines it with the values of any number of observables inputs. The zipWith operator is RxJS 8's replacement for the deprecated zip operator. You could do something similar like:

import { zipWith } from 'rxjs';

private createResult() {
   this.userObservable.getFullName().pipe(
      zipWith(
        this.userObservable.getPhoneNumber(),
        this.userObservable.getEmailAddress()
      ),
      map(([fullName, phoneNumber, emailAddress]) => this.httpService.createSomething(fullName, phoneNumber, emailAddress))
    ).subscribe((result) => console.log(result))
  }

That approach has the benefit that your are not nesting multiple subscriptions inside each other which may lead to unintended side-effects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文