Home > Blockchain >  Angular canActivate httpClient infinite loop
Angular canActivate httpClient infinite loop

Time:03-14

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?

CodePudding user response:

Try this:

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

CodePudding user response:

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