您可以在组件内部使用等效的异步管道吗? [英] is there an equivalent of async pipe that you can use inside a component?

查看:83
本文介绍了您可以在组件内部使用等效的异步管道吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的组件中是否存在与async管道等效的东西

Does there exist something equivalent to the async pipe that I could use inside a component like this

   @Component({
      selector: 'my-component',
    })

    export class myComponent {

      myObservable$: Observable<string>;

      method() {
        doSomething(this.myObservable$);
        // here I would like to access directly the current string value of
        // myObservable$ without having to subscribe 
      }
    }

推荐答案

您必须问自己:避免使用subscribe()调用要达到什么目的?我的猜测是,您想防止保留订阅,而不必手动取消订阅.

You have to ask yourself: What do you want to achieve by avoiding the subscribe() call? My guess is that you want to prevent keeping the subscription around and having to unsubscribe manually.

如果是这种情况,则只需确保获得一个完整的Observable.这样就无需以后取消订阅了.您可以将任何Observable(有限或无限)转换为最终完成的.

If this is the case, you just have to make sure you get an Observable that completes. Then there is no need to unsubscribe later. You can convert any Observable (finite or infinite) to one that will eventually complete.

以下是您的案例示例:

  method() {
    this.myObservable$.take(1).subscribe(
      val => doSomething(val)
    );
  }

正确的方法实际上取决于您的可观察对象做什么以及您希望使用该值做什么.例如,Angular2 http呼叫自己完成,

The correct way really depends on what your observable does and what you want to do with the value. Angular2 http calls for example complete on their own, no need to unsubscribe!

或者,如果您想为可观察对象中的每个新值调用doSomething,则上述解决方案将不合适,因为您仅获得第一个值,然后可观察对象完成了.正如我所说的,这取决于问题的背景.

Or if you want to call doSomething for every new value in your observable, the above solution won't fit because you only get the first value, then the observable completes. As I said, this comes down to the context of the problem.

这篇关于您可以在组件内部使用等效的异步管道吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆