typescript Angular 2:将可观察转化为承诺

gkl3eglg  于 2023-01-03  发布在  TypeScript
关注(0)|答案(8)|浏览(155)
    • Q)如何将下面的可观察值转换为承诺值,以便使用.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;
    });      
  }

谢谢!

ff29svar

ff29svar1#

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.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));
});
91zkwejq

91zkwejq2#

可观察性可以像这样转化为承诺:

let promise=observable.toPromise();
yeotifhr

yeotifhr3#

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

import 'rxjs/add/operator/first';

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

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

fxnxkyjh

fxnxkyjh4#

在你的情况下,做出可遵守承诺的正确方法是

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

4smxwvx55#

    • 编辑:**

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

    • 新答案:**

作为已弃用的toPromise()方法的替代方法,应使用两个内置静态转换函数firstValueFrom或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已经过时,但正如您在这里看到的,它并没有。
因此,请使用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);

了解更多here.
注:否则你可以使用.pipe(take(1)).toPromise,但正如所说,你应该没有任何问题,使用上述例子。

pbwdgjma

pbwdgjma6#

    • 用途:**

1.第一个月
当我们对值流感兴趣时使用。工作方式类似于以前的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
}
alen0pnh

alen0pnh7#

您可以将Observable转换为promise,只需一行代码,如下所示:

let promisevar = observable.toPromise()

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

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

whlutmcx8#

我喜欢生的,所以这一个,因为**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

相关问题