【问题标题】:Error Static Injector: StaticInjectorError(AppModule)[GameService -> HttpClient]错误静态注入器:StaticInjectorError(AppModule)[GameService -> HttpClient]
【发布时间】:2024-05-21 22:50:01
【问题描述】:

我对 Angular 中的库有疑问。我已经完成了一个库,我在其中使用 HttpClient 询问 API,但是有一个问题,当我尝试从这个库 GameService 中继续一个类时,我收到:“Error Static Injector: StaticInjectorError(AppModule)[GameService -> HttpClient]” .当我看到这一点时,我尝试在我的应用程序中导入 HttpModule 并添加提供程序 HttpClient 但没有任何改变。 这是我的类库的代码:

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Game } from './model/game';
import { Observable } from 'rxjs';
import { EndPointGetterService } from '../utilities/end-point-getter.service';

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

  private gameUrl = localStorage.getItem('endpoint') + '/Games';
  private headers: HttpHeaders;

  constructor(private http: HttpClient, private EPGetter: EndPointGetterService) {
    this.headers = new HttpHeaders({
      'Access-Control-Allow-Origin': 'http://localhost:4200',
      'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
      'Access-Control-Allow-Headers': '*',
    });
  }
  getStateGame(groupName: string): Observable<number> {
    return this.http.get<number>(this.EPGetter.getEndPointUrl() + '/Games/' + groupName + '/State', { headers: this.headers });
  }

在我的应用程序中,我的 app.module.ts 中有这个:

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { GameService } from '@oneroomic/oneroomlibrary';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    LockscreenComponent,
    SettingsComponent
  ],
  imports: [
    HttpClientModule,
  ],
  providers: [
    HttpClient,
    GameService
  ],

这就是我注入 GameService 的方式:

constructor(
  private snackBar: MatSnackBar,
  private gameService: GameService
  ) {}

【问题讨论】:

  • 您好,您的 Angular 版本是多少?
  • 请从提供者中移除 httpClient 和 gameservice。这里不需要设置。
  • 错误:未捕获(在承诺中):错误:必须从注入上下文调用注入()错误:必须从注入上下文调用注入()
  • 这就是我删除它时收到的内容,我的角度版本是 7
  • 从 '@oneroomic/oneroomlibrary' 中删除此导入 { GameService };来自 app.module.ts

标签: angular angular-library


【解决方案1】:

尝试从提供者中删除 GameService,就像 providedIn: 'root' 一样。而且那里也不需要HttpClient

【讨论】:

  • 我已经在 Providers 中没有 GameService 的情况下进行了测试,但我遇到了另一个错误
  • 错误:未捕获(在承诺中):错误:必须从注入上下文调用注入()错误:必须从注入上下文调用注入()
  • 我编辑了我的帖子以展示我如何注入我的组件
  • 你能把组件代码发过来吗
【解决方案2】:

好的,所以问题是我试图在本地安装这个库,但是当我在 NPM 上发布时,它起作用了。显然,当我尝试在本地安装时出现问题。

【讨论】: