'Angular canActivate httpClient infinite loop

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?



Solution 1:[1]

Try this:

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lorraine R.
Solution 2 Almost