Having trouble using guards for an unlogged user and constantly facing errors.
Error: TS7030 - Not all code paths return a value.
Below is my auth.guard.ts file:
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private auth:AuthService,
private router:Router,
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree
{
if (this.auth.isAuthenticated()) {
return true;
} else {
this.auth.logout();
this.router.navigate(['/admin', 'login'], {
queryParams: {
loginAgain: true}
});
}
}
}
Here's the structure of my auth service file:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, Subject, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { FbAuthResponse, User } from '../../../shared/interfaces';
import { environment } from '../../../../environments/environment';
@Injectable({ providedIn: 'root' })
export class AuthService {
constructor(private http: HttpClient) {}
public error$: Subject<string> = new Subject<string>();
get token(): string {
const expDate = new Date(localStorage.getItem('fb-token-expires'));
if (new Date() > expDate) {
this.logout();
return null;
}
return localStorage.getItem('fb-token');
}
login(user: User): Observable<any> {
user.returnSecureToken = true;
return this.http.post(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${environment.apikey}`, user)
.pipe(
tap<any>(this.setToken),
catchError(this.handleError.bind(this)),
);
}
logout() {
this.setToken(null);
}
isAuthenticated() {
return !!this.token;
}
private setToken(response: FbAuthResponse | null) {
if (response) {
const expDate = new Date(new Date().getTime() + +response.expiresIn * 1000);
localStorage.setItem('fb-token', response.idToken);
localStorage.setItem('fb-token-exp', expDate.toString());
} else {
localStorage.clear();
}
}
}
Also attempted to resolve the error by modifying the method as such:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
):
Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree
{
return this.auth.isAuthenticated()
.pipe(map((isAuthenticated) => isAuthenticated || this.router.createUrlTree([''])))
}}
However, encountered another error related to pipe usage:
Error: ts2339 - Property 'pipe' does not exist on type 'boolean'
I'm questioning whether there's an issue with how I'm passing data in the initial method, considering adding another return function. The 'if' statement may also be unnecessary here.