Reputation: 2974
The examples at https://angular.io/tutorial/tour-of-heroes/toh-pt6#tap-into-the-observable don't work.
This used to work but something in Angular must have changed and now it doesn't work any more and I don't understand what to do to make it work -- is this still the right way of doing it or has it changed?
init(): Promise<Settings> {
return this.http.get<Settings>('settings').pipe(
tap(response => this.settings = response)
).toPromise<Settings>();
}
error TS2322: Type 'Promise<Settings | undefined>' is not assignable to type 'Promise<Settings>'.
Type 'Settings | undefined' is not assignable to type 'Settings'.
Type 'undefined' is not assignable to type 'Settings'.
Upvotes: 0
Views: 644
Reputation: 1771
toPromise
was deprecated in RxJS 7 which introduced the breaking change you are experiencing: https://rxjs.dev/deprecations/to-promise
..the return type of the Observable's toPromise() method has been fixed to better reflect the fact that Observables can yield zero values. This may be a breaking change to some projects as the return type was changed from Promise to Promise<T | undefined>.
Assuming you want to keep using promises, the recommendation is to use either:
For example:
import { withLatestFrom } from 'rxjs/operators';
init(): Promise<Settings> {
const getSettings$: Observable<Settings> =
this.http.get<Settings>('settings')
.pipe(
tap(response => this.settings = response)
);
return firstValueFrom(getSettings$)
}
Upvotes: 1