繁体   English   中英

Angular 2:将Observable转换为Promise

[英]Angular 2: Convert Observable to Promise

问)如何将以下可观察值转换为 promise 以便我可以使用 .then .then(...)调用它?

我想转换为 promise 的方法:

  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

不要管。 默认情况下,它位于 Observable 对象上。

 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));
});

observable 可以像这样转换为 promise:

let promise=observable.toPromise();

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

import 'rxjs/add/operator/first';


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

first() 确保订阅块只被调用一次(之后就好像你从未订阅过一样),与 promise 完全一样 then()

使 Observable 成为 Promise 的正确方法,在您的情况下将遵循

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

很多评论都声称不推荐使用toPromise但正如您在此处看到的那样事实并非如此。

所以请使用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);
  });

异步/等待示例:

//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);

在这里阅读更多。

并且请删除这个错误的声明,说toPromise已被弃用。


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

toPromise 在 RxJS 7 中弃用

使用:

  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');

我喜欢生的,所以这个因为toPromise()已经不存在了

   const status = await new Promise<boolean>((resolve, reject) => {
     someObs$.subscribe({
      next: resolve,
      error: reject,
    });
  });

一种复杂的方法是使用https://rxjs.dev/api/index/function/lastValueFrom

  const replyTo = new AsyncSubject();

  replyTo.next(false);
  replyTo.next(false);
  replyTo.next(true);

  replyTo.complete();

  const status = await lastValueFrom(replyTo) // true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM