0

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?

ame
  • 773
  • 9
  • 21

2 Answers2

0

Try this:

return this.authService.refresh().pipe(
        take(1),
        switchMap(() => {
            return of(true);
        }),
        catchError(() => {
            this.router.navigate('/login');
            return of(false);
        })
    );
Lorraine R.
  • 1,545
  • 1
  • 14
  • 39
0

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;
        })
    );
}
spaleet
  • 838
  • 2
  • 10
  • 23