【问题标题】:Observable: Return the result of a Promise until unsubscribedObservable:返回 Promise 的结果,直到取消订阅
【发布时间】:2016-08-30 14:51:41
【问题描述】:

我想编写一个返回 Observable 订阅的函数。 Observable 应该每三秒发出一次 Promise 的结果。

以下函数返回 Promise,但我希望它返回 Promise 的结果:

public static getWifiInfos(): Observable<Promise<ConnectionInfo>> {
    return Observable
        .interval(3000)
        .map(() => Hotspot.getConnectionInfo());
}

我正在使用 Angular 和 TypeScript。

【问题讨论】:

    标签: angular typescript observable


    【解决方案1】:

    您需要的是switchMap,它将您的间隔映射到另一个 Observable 的输出。我不知道如何形容它更好。

    public static getWifiInfos(): Observable<ConnectionInfo> {
      return <Observable<ConnectionInfo>> Observable
        .interval(3000)
        .switchMap(() => 
          Observable.fromPromise(Hotspot.getConnectionInfo())
        )
    }
    

    【讨论】:

      【解决方案2】:

      你可以试试下面,

         private connectionInfoSubject = new Subject<ConnectionInfo>();
      
         connectionInfoObservable = this.connectionInfoSubject.asObservable();
      
         public static getWifiInfos(): Observable<ConnectionInfo>{
             Observable
              .interval(3000)
              .map(() => {
                  // Assuming Hotspot.getConnectionInfo is a synchronous call                
                  this.connectionInfoSubject.next(Hotspot.getConnectionInfo());
                 // If Hotspot.getConnectionInfo is promise
                 Hotspot.getConnectionInfo().then(result => {
                      this.connectionInfoSubject.next(result);
                 })
              });
         }
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2021-09-02
        • 1970-01-01
        • 2020-05-30
        • 2018-03-09
        • 2019-03-19
        • 1970-01-01
        • 2020-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多