简体   繁体   English

Angular 2:将Observable转换为Promise

[英]Angular 2: Convert Observable to Promise

Q) How do I convert the following observable to a promise so I can call it with .then(...) ?问)如何将以下可观察值转换为 promise 以便我可以使用 .then .then(...)调用它?

My method I want to convert to a promise:我想转换为 promise 的方法:

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

The service method it calls:它调用的服务方法:

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

Thanks!谢谢!

rxjs7 rxjs7

lastValueFrom(of('foo'));

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

rxjs6 rxjs6

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

Don't pipe.不要管。 It's on the Observable object by default.默认情况下,它位于 Observable 对象上。

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

rxjs5 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();

you dont really need to do this just do ...你真的不需要这样做只是做...

import 'rxjs/add/operator/first';


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

first() ensures the subscribe block is only called once (after which it will be as if you never subscribed), exactly the same as a promises then() first() 确保订阅块只被调用一次(之后就好像你从未订阅过一样),与 promise 完全一样 then()

The proper way to make Observable a Promise, in your case would be following使 Observable 成为 Promise 的正确方法,在您的情况下将遵循

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

A lot of comments are claiming toPromise deprecated but as you can see here it's not.很多评论都声称不推荐使用toPromise但正如您在此处看到的那样事实并非如此。

So please juste use toPromise (RxJs 6) as said:所以请使用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 example:异步/等待示例:

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

Read more here .在这里阅读更多。

And please remove this wrong claim saying toPromise is deprecated.并且请删除这个错误的声明,说toPromise已被弃用。


Note: Otherwise you can use .pipe(take(1)).toPromise but as said you shouldn't have any problem using above example.注意:否则您可以使用.pipe(take(1)).toPromise但如上所述,使用上面的示例应该没有任何问题。

toPromise is deprecated in RxJS 7. toPromise 在 RxJS 7 中弃用

Use:使用:

  1. lastValueFrom

Used when we are interested in the stream of values.当我们对值流感兴趣时使用。 Works like the former toPromise像以前的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
}

You can convert Observable to promise just by single line of code as below:您可以通过如下一行代码将 Observable 转换为 promise:

let promisevar = observable.toPromise()

Now you can use then on the promisevar to apply then condition based on your requirement.现在您可以在 promisevar 上使用 then 根据您的要求应用 then 条件。

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

I like it raw so this one since toPromise() is no more我喜欢生的,所以这个因为toPromise()已经不存在了

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

A sophisticated way is using https://rxjs.dev/api/index/function/lastValueFrom一种复杂的方法是使用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