Home > Back-end >  Observable subscription error after rxjs update
Observable subscription error after rxjs update

Time:04-29

This piece of code was working fine

export function appInitializer(accountService: AccountService) {
    return () => new Promise(resolve => {
        // attempt to refresh token on app start up to auto authenticate
        accountService.refreshToken()
            .subscribe()
            .add(resolve);
    });
}

but now after updating rxjs from version 6.5.5 to 7.4.0, I have this error when I add resolve to the Subscription :

(parameter) resolve: (value: unknown) => void Argument of type '(value: unknown) => void' is not assignable to parameter of type 'TeardownLogic'. Type '(value: unknown) => void' is not assignable to type '() => void'.ts(2345) app.initializer.ts(8, 18): Did you mean to call this expression?

The angular project I am trying to modify is available here

My noob question is: How can I get this code to work again without having to go back to rxjs v6.5.5?

CodePudding user response:

Try this

accountService.refreshToken()
        .subscribe()
        .add(()=>resolve());

or even better

export function appInitializer(accountService: AccountService) {
    return () => new Promise((resolve,reject) => {
        // attempt to refresh token on app start up to auto authenticate
        accountService.refreshToken().subscribe(()=>resolve,err=>reject(err))
    });

}

But this is how I would probably do it

export function appInitializer(accountService: AccountService) {
    return () => accountService.refreshToken()
    }

Here you have a working demo

https://stackblitz.com/edit/angular-gl1dnd?file=src/app/app.module.ts

check the console, it shows that both initializers are running on startup

CodePudding user response:

I think the best approach is to use firstValueFrom:

import { Observable, firstValueFrom } from 'rxjs';

interface AccountService {
  refreshToken: () => Observable<unknown>
}

export function appInitializer(accountService: AccountService) {
    return () => firstValueFrom(accountService.refreshToken());
}
  • Related