Home > Mobile >  TS7030: Not all code paths return a value. Guard, canActivate method Angular13
TS7030: Not all code paths return a value. Guard, canActivate method Angular13

Time:06-01

I am trying to use guards for an unlogged user, but ts always returns an error

TS7030: Not all code paths return a value.

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

my auth service file looks like this:

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 tried to get rid of the error that way:

  canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot,
      ):
       Observable<boolean | UrlTree> 
      | Promise<boolean | UrlTree> 
      | boolean 
      | UrlTree
       
      {
        return this.auth.isAuthenticated()
          .pipe(map((isAuthenticated) => isAuthenticated || this.router.createUrlTree([''])))
      }}

But in this case I am getting another error, related to the pipe usage:

ts2339: property 'pipe' does not exist on type 'boolean'

I wonder if there is any issue with the way I am passing the data in the first method and I should add one more return to the function. May be the 'if' construction is unnecessary in here.

CodePudding user response:

A couple of observations:

TS7030: Not all code paths return a value.

This message will be displayed when you don't provide a default return value. For example:

getUserById(string: id): User {
  // this function will only return a value if id is valid
  if (id) { 
    // some logic...
    return this.theUser;     
  }
}

The solution will be to add an else statement, or even better, add the return value

getUserById(string: id): User {
  if (id) { 
    return this.theUser;     
  }

  return this.emptyUser; // your default return value
}

ts2339: property 'pipe' does not exist on type 'boolean'

The pipe operator is a method for the Observable interface that can be used to combine multiple RxJS operators to compose asynchronous operations.

Your isAuthenticated() returns a boolean, a primitive value.

This will work if you return an Observable using, for example, the of operator.

isAuthenticated(): Observable<boolean> {
 return of(!!this.token);
}
  • Related