Angular 2: Convert Observable to Promise

后端 未结 7 624
耶瑟儿~
耶瑟儿~ 2020-11-27 18:00

Q) How do I convert the following observable to a promise so I can call it with .then(...)?

My method I want to convert to a promise:

相关标签:
7条回答
  • 2020-11-27 18:36

    toPromise is deprecated in RxJS 7.

    Use:

    1. lastValueFrom

    Used when we are interested in the stream of values. Works like the former toPromise

    Example

    public async getAssetTypes() {
      const assetTypes$ = this._APIService.getAssetTypes()
      this.assetTypes = await lastValueFrom(assetTypes$);
    }
    
    1. firstValueFrom

    Used when we are not interested in the stream of values but just the first value and then unsubscribe from the stream

    public async getAssetTypes() {
      const assetTypes$ = this._APIService.getAssetTypes()
      this.assetTypes = await firstValueFrom(assetTypes$); // get first value and unsubscribe
    }
    
    0 讨论(0)
提交回复
热议问题