Angular canActivate httpClient infinite loop

273 Views Asked by At

I have code like this:

auth.guard.ts

canActivate(): void {
    const token = localStorage.getItem('token');
    const refreshToken = localStorage.getItem('refreshToken');

    if (!token || !refreshToken) {
        this.router.navigate('/login');
        return false;
    }

    return this.authService.refresh().pipe(
        map(() => { return true; }),
        catchError(() => {
            this.router.navigate('/login');
            return of(false);
        })
    );
}

auth.service.ts

refresh(): Observable<any> {
    return this.httpClient.post<any>(
        environment.apiUrl+'/auth/token',
        {
            refreshToken: localStorage.getItem('refreshToken')
        },
        { headers: this.headers }
    );
}

But the row "return this.authService.refresh().pipe(" makes infinite loop.

What could be wrong if I return Angular HttpClient Observable from canActivate() method?

What is the reason of infinite loop in this case?

2

There are 2 best solutions below

1
On

Try this:

return this.authService.refresh().pipe(
        take(1),
        switchMap(() => {
            return of(true);
        }),
        catchError(() => {
            this.router.navigate('/login');
            return of(false);
        })
    );
0
On

Change canActivate() to this :

canActivate(): boolean {
    const token = localStorage.getItem('token');
    const refreshToken = localStorage.getItem('refreshToken');

    if (!token || !refreshToken) {
        this.router.navigate('/login');
        return false;
    }

    return this.authService.refresh().pipe(
        map(() => return true),
        catchError(() => {
            this.router.navigate('/login');
            return false;
        })
    );
}