繁体   English   中英

JWT 库错误:通用类型 'ModuleWithProviders<t> ' 在 Angular 10 中需要 1 个类型参数</t>

[英]JWT library error: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s) in Angular 10

对于我正在使用的身份验证项目:

Angular CLI: 11.0.4

Node: 10.19.0

OS: linux x64

我在ng serve之后收到以下错误,我不确定为什么会这样,错误似乎在库node_modules/angular2-jwt/angular2-jwt.d.ts而不是在我写的代码中:

node_modules/angular2-jwt/angular2-jwt.d.ts:88:41 - 错误 TS2314:通用类型“ModuleWithProviders”需要 1 个类型参数。

static forRoot(配置:AuthConfig):ModuleWithProviders;

也与此相关(所以我相信错误是并发的,甚至,我担心,是可以互换的),因为它会在显示'ModuleWithProviders<T>'错误后立即显示,所以我认为显示它们是有意义的两者都链接在一起:

错误:node_modules/angular2-jwt/angular2-jwt.d.ts:1:77 - 错误 TS2307:找不到模块“@angular/http”或其相应的类型声明。

1 从“@angular/http”导入 { Http, Request, RequestOptions, RequestOptionsArgs, Response };

所以我遇到的困难也是由于我不确定代码的哪些部分受到影响所以为了完整性我将放置app.module.ts和包含 jwt 的文件jwt include

应用程序模块.ts

import { ValidateService } from './services/validate.service';
import { FlashMessagesModule } from 'angular2-flash-messages'; 
import { HttpClientModule } from '@angular/common/http';
import { AuthService } from './services/auth.service'; 
import { AuthGuard } from './guards/auth.guards';


const appRoutes: Routes = [
  {path:'', component: HomeComponent},
  {path:'register', component: RegisterComponent},
  {path:'login', component: LoginComponent},
  {path:'dashboard', component: DashboardComponent, canActivate: [AuthGuard]},
  {path:'profile', component: ProfileComponent, canActivate: [AuthGuard]},
]

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    LoginComponent,
    RegisterComponent,
    HomeComponent,
    DashboardComponent,
    ProfileComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
    FlashMessagesModule.forRoot(),
    HttpClientModule,
  ],
  providers: [ValidateService, AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

授权服务.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { tokenNotExpired } from 'angular2-jwt';


@Injectable({
  providedIn: 'root'
})
export class AuthService {
  authToken: any;
  user: any;

  constructor(private httpClient: HttpClient) { }

  registerUser(user) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
    };
    return this.httpClient.post('http://localhost:3000/users/register', user, httpOptions);
  }

  authenticateUser(user) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
    };
    return this.httpClient.post('http://localhost:3000/users/authenticate', user, httpOptions);
  }

  getProfile() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        Authorization: this.authToken,
      })
    };
    this.loadToken();
    return this.httpClient.get('http://localhost:3000/users/profile', httpOptions);
  }

  storeUserData(token, user) {
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  loadToken() {
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  loggedIn() {
    return tokenNotExpired();
  }

  logout() {
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}

配置文件.components.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';  

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  user: Object = {};

  constructor(private authService: AuthService, private router: Router) { }

  ngOnInit(): void {
    this.authService.getProfile().subscribe(profile => {
      this.user = profile;
    },
    err => {
      console.log(err);
      return false;
    })
  }
}

我研究了如何解决这个问题,到目前为止我能找到的是: 这篇文章非常有用,因为它有我同样的问题。 答案要求 错误报告回购,但是,没有提供任何答案。 提供的答案建议插入以下代码:

declare module "@angular/core" {
  interface ModuleWithProviders<T = any> {
    ngModule: Type<T>;
    providers?: Provider[];
  }
}

不幸的是,这不是一个可以接受的答案,我不确定我可以把这段代码放在我上面提供的app.module.ts的任何部分。

我也研究了这篇文章,它也很有用,但没有使用上面的建议。 我从错误中了解到的奇怪事实是它似乎来自库本身,而不是来自我编写的代码。

在此之后,我继续:

  1. rm -rf所有 node_modules
  2. rm -rf package jason 文件
  3. 清理缓存
  4. npm install

但结果是一样的,我总是在同一个图书馆收到同样的错误。 如果有人遇到同样的问题,请分享一下它是如何解决的,以及我应该做些什么来解决这个问题。

将这段代码插入angular2-jwt.d.ts class 并确认class的变化:

declare module "@angular/core" {
      interface ModuleWithProviders<T = any> {
        ngModule: Type<T>;
        providers?: Provider[];
      }
    }

但是你应该使用比这更新的库,比如@auth0/angular-jwt安装这个库后,你必须在 class app.module.ts中注册它的模块:

  import {JwtModule} from '@auth0/angular-jwt'


  imports: [
     JwtModule.forRoot({
        config: {
          tokenGetter:() => {
             return localStorage.getItem('access_token'); 
          },
        },
     })
  ],

然后你可以在你的 AuthService class 中使用它:

 import {JwtHelperService} from '@auth0/angular-jwt';

 constructor(public jwtHelper: JwtHelperService) {
   }

 isAuthenticated(): boolean {
    return !this.jwtHelper.isTokenExpired(this.token);
  }

所有这些都在带有示例的简短文档中进行了解释 ( https://www.npmjs.com/package/@auth0/angular-jwt ),所以在使用任何库之前不要偷懒阅读它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM