1

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

类型 'typeof AuthServiceService' 不可分配给类型 '(request?: HttpRequest) => string | 承诺'。类型 'typeof AuthServiceService' 提供不匹配的签名 '(request?: HttpRequest): string

这是我的 auth-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 的响应应该是什么样子吗?

4

2 回答 2

1

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

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

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

于 2020-10-10T15:51:30.617 回答
0

您的代码似乎很好(至少对我而言),除了一个问题是在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)
  }
于 2020-10-10T15:22:18.487 回答