【问题标题】:When would you not want to subscribe to an observable in Angular?你什么时候不想订阅 Angular 中的 observable?
【发布时间】:2021-12-13 13:57:06
【问题描述】:

我在 Angular 中发现了 Observables 和 Promise 之间的区别。优点之一是可观察对象是“惰性的”,因为它只有在订阅时才会调用。但是,你什么时候不想订阅 observable?

【问题讨论】:

    标签: angular typescript observable


    【解决方案1】:

    为一个做类似事情的服务提供图像

    interface Foo {
      id: number;
    }
    public loadStuffFromApiEndpoint(): Observable<Foo> {
       return this.http.get<Foo>('...')
    }
    

    现在,如果您需要添加例如您想在两个不同的地方使用服务器响应的时间戳,您可以想象另一个服务功能,例如

    interface FooExtended extends Foo {
      createdAt: number;
    }
    public loadAndEnrichStuffFromApiEndpoint(): Observable<FooExtended> {
      return this.loadStuffFromApiEndpoint().pipe(map(e => e.loadedAt: Date.now()))
    }
    

    这样你就不用订阅 Observable,而是通过管道来丰富它。

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 1970-01-01
      • 2018-05-08
      • 2020-06-19
      • 2018-12-12
      • 2017-11-30
      • 2018-07-13
      • 2019-01-20
      • 2019-02-17
      相关资源
      最近更新 更多