TS7030:并非所有代码路径 return 一个值。 Guard, canActivate 方法 Angular13

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

我正在尝试为未登录的用户使用防护,但总是 return 出现错误

TS7030: Not all code paths return a value.

我的 auth.guard.ts 文件:

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

我的授权服务文件如下所示:

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

}

也尝试以这种方式消除错误:

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

但在这种情况下,我收到另一个与管道使用相关的错误:

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

我想知道我在第一种方法中传递数据的方式是否有任何问题,我应该在函数中再添加一个 return。可能是这里不需要 'if' 构造。

一些观察:

TS7030: Not all code paths return a value.

当您不提供默认 return 值时,将显示此消息。例如:

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

解决方案是添加一个 else 语句,或者更好的是,添加 return

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'

pipe 运算符是 Observable 接口的一种方法,可用于组合多个 RxJS 运算符以组成异步操作。

你的 isAuthenticated() return 是一个 boolean,原始值。

如果您 return 一个 Observable 使用 of 运算符,这将起作用。

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