Angular 2:将 Observable 转换为 Promise

Angular 2: Convert Observable to Promise

Q) 如何将以下可观察对象转换为 Promise,以便我可以用 .then(...) 调用它?

我想转换为承诺的方法:

  this._APIService.getAssetTypes().subscribe(
    assettypes => {
        this._LocalStorageService.setAssetTypes(assettypes);
    },
    err => {
        this._LogService.error(JSON.stringify(err))
    },
    () => {}
  ); 

它调用的服务方法:

  getAssetTypes() {
    var method = "assettype";
    var url = this.apiBaseUrl + method;

    return this._http.get(url, {})
      .map(res => <AssetType[]>res.json())
      .map((assettypes) => {
        assettypes.forEach((assettypes) => {
          // do anything here you might need....
      });
      return assettypes;
    });      
  }  

谢谢!

rxjs7

lastValueFrom(of('foo'));

https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated

rxjs6

https://github.com/ReactiveX/rxjs/issues/2868#issuecomment-360633707

Don't pipe. It's on the Observable object by default.

Observable.of('foo').toPromise(); // this

rxjs5

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

...

this._APIService.getAssetTypes()
.map(assettypes => {
  this._LocalStorageService.setAssetTypes(assettypes);
})
.toPromise()
.catch(err => {
  this._LogService.error(JSON.stringify(err));
});

你真的不需要这样做只是做...

import 'rxjs/add/operator/first';


this.esQueryService.getDocuments$.first().subscribe(() => {
        event.enableButtonsCallback();
      },
      (err: any) => console.error(err)
    );
    this.getDocuments(query, false);

first() 确保订阅块只被调用一次(之后就像您从未订阅过一样),与承诺 then()

完全相同

observable 可以像这样转换为 promise:

let promise=observable.toPromise();

使 Observable 成为 Promise 的正确方法,在您的情况下是以下

getAssetTypesPromise() Observable<any> {
  return new Promise((resolve, reject) => {
      this.getAssetTypes().subscribe((response: any) => {
        resolve(response);
      }, reject);
    });
}

编辑:

.toPromise() 现在已在 RxJS 7 中弃用(来源:https://rxjs.dev/deprecations/to-promise

新答案:

As a replacement to the deprecated toPromise() method, you should use one of the two built in static conversion functions firstValueFrom or lastValueFrom.

示例:

import { interval, lastValueFrom } from 'rxjs';
import { take } from 'rxjs/operators';
 
async function execute() {
  const source$ = interval(2000).pipe(take(10));
  const finalNumber = await lastValueFrom(source$);
  console.log(`The final number is ${finalNumber}`);
}
 
execute();
 
// Expected output:
// "The final number is 9"

旧答案:

许多评论声称 toPromise 已弃用,但如您所见 here 事实并非如此。

所以请按照说明使用 toPromise (RxJs 6):

//return basic observable
const sample = val => Rx.Observable.of(val).delay(5000);
//convert basic observable to promise
const example = sample('First Example')
  .toPromise()
  //output: 'First Example'
  .then(result => {
    console.log('From Promise:', result);
  });

async/await 示例:

//return basic observable
const sample = val => Rx.Observable.of(val).delay(5000);
//convert basic observable to promise
const example = await sample('First Example').toPromise()
// output: 'First Example'
console.log('From Promise:', result);

阅读更多here


注意:否则您可以使用 .pipe(take(1)).toPromise,但如前所述,使用上面的示例应该没有任何问题。

toPromise 在 RxJS 7.

中是 deprecated

使用:

  1. lastValueFrom

当我们对值流感兴趣时使用。像以前一样工作 toPromise

示例

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

当我们对值流不感兴趣而只对第一个值感兴趣然后取消订阅流时使用

public async getAssetTypes() {
  const assetTypes$ = this._APIService.getAssetTypes()
  this.assetTypes = await firstValueFrom(assetTypes$); // get first value and unsubscribe
}

只需一行代码,您就可以将 Observable 转换为 Promise:

let promisevar = observable.toPromise()

现在您可以在 promisevar 上使用 then 来根据您的要求应用 then 条件。

promisevar.then('Your condition/Logic');