Requirements: The project needs to convert Observables to Promises and wait for completion, and when using the toPromise() method in an Angular project, the hint has been deprecated, and then it is recommended to use the firstValueFrom or lastValueFrom static methods.
Why deprecate the toPromise() method?
Because the toPromise() method name never indicates which emitted value the Promise will resolve, because Observables can produce multiple values over time. When converting to a Promise, you may want to choose whether you want to select the first value to arrive or the last value. To solve all these problems, we decided to deprecate toPromise() and introduce two new helper functions for converting to promises.
Simply understandObservables produce multiple valuesAnd thenPromises will only result in one valueThen, some users want to use the first value, and some users want to use the last value, so firstValueFrom and lastValueFrom appear. (Note: toPromise() is the last value to get the observables)
firstValueFrom example
You may want to get the first value when it arrives without waiting for the Observable to complete, so you can use firstValueFrom. firstValueFrom will resolve the Promise with the first value emitted by the Observable and immediately unsubscribe to preserve the resource. If the Observable completes without emitting any value, the firstValueFrom will also be rejected with an EmptyError.
lastValueFrom example
lastValueFrom is almost identical to toPromise(), which means it will parse with the last value reached when the Observable completes, but behaves differently when the Observable completes without emitting a single value. When the Observable completes without being fired, toPromise() will successfully resolve to undefined (so the return type changes), and lastValueFrom will be rejected as EmptyError. Therefore, the return type of lastValueFrom is Promise<T>, just like toPromise() in RxJS 6.
Example parsing
In RxJS, interval(1000) generates an observable that emits an incremental sequence of numbers every 1000 milliseconds (i.e., 1 second), starting at 0.
Next, .pipe(take(10)) is an operator chain that limits the number of elements that the Observable emits. Here, take(10) means that only the values of the first 10 emitted are taken.
Let's explain this expression in detail:
interval(1000): Create an observable that emits a number every 1 second. The number sequence starts at 0 and increases by 1 each time.
.pipe(take(10)): Use the .pipe() method to connect multiple operators. Here we use the take(10) operator, which limits the Observable to emit only the first 10 values.
Test for EmptyError errors
The code is as follows:
or
Reference:The hyperlink login is visible. |