Angular - 响应不能分配给类型'request?: HttpRequest<any>

Angular - Response is not assignable to type 'request?: HttpRequest<any>

我尝试在 Angular 中编写 AuthGuard,但出现以下错误:

Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceService' provides no match for the signature '(request?: HttpRequest): string

这是我的授权-service.service.ts:

@Injectable({
  providedIn: 'root'
})
export class AuthServiceService {

  constructor(
    private http:HttpClient,
    public jwtHelper: JwtHelperService) { }
  login(data):Observable<any>{
    return this.http.post(baseUrl + 'ApplicationUser/login' ,data)

  }

  handleError(error: HttpErrorResponse) {
    return throwError(error);
  }

  public isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    return !this.jwtHelper.isTokenExpired(token);
  }

}

这是我的 AuthGuard 服务:

import { AuthServiceService } from 'src/services/auth/auth/auth-service.service';
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(public auth: AuthServiceService, public router: Router) { }
  
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['']);
      return false;
    }
    return true;
  }
}

我在 tokenGetter 的这一行收到这个错误:

const JWT_Module_Options: JwtModuleOptions = {
  config: {
    tokenGetter: AuthServiceService
  }
};

谁能帮我看看 AuthService 的响应应该是什么样子的?

您的代码看起来不错(至少对我而言),除了一个问题是 constructor

中的初始化方法
 constructor(private http:HttpClient,
    public jwtHelper: JwtHelperService) { }
  login(data):Observable<any>{
    return this.http.post(baseUrl + 'ApplicationUser/login' ,data)

  }

将此更改为以下内容

  constructor(private http:HttpClient, public jwtHelper: JwtHelperService) { }
    
  login(data): Observable<any> {
      return this.http.post(baseUrl + 'ApplicationUser/login' ,data)
  }

经过一番研究,我找到了解决方案。 tokenGetter 选项需要一个带有我的令牌的字符串 - 所以我从本地存储返回令牌,如下所示:

const JWT_Module_Options: JwtModuleOptions = {
  config: {
    tokenGetter: () => {
      return localStorage.getItem('token')
    }
  }
};

现在我的 AuthGuard 可以正常工作了:) 谢谢大家的帮助! :)