角度2: 将可观察到的转换为承诺

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

谢谢!

140703 次浏览

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

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

observable can be converted to promise like this:

let promise=observable.toPromise();

The proper way to make Observable a Promise, in your case would be following

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

Edit:

.toPromise() is now deprecated in RxJS 7 (source: https://rxjs.dev/deprecations/to-promise)

New answer:

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

Example:

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"

Old answer:

A lot of comments are claiming toPromise deprecated but as you can see here it's not.

So please juste use toPromise (RxJs 6) as said:

//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.


Note: Otherwise you can use .pipe(take(1)).toPromise but as said you shouldn't have any problem using above example.

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
}

You can convert Observable to promise just by single line of code as below:

let promisevar = observable.toPromise()

Now you can use then on the promisevar to apply then condition based on your requirement.

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