debugging 错误:未捕获(在promise中):空注入器错误:R3InjectorError(AppModule)Angular 13

hgtggwj0  于 2023-05-07  发布在  Angular
关注(0)|答案(2)|浏览(188)

当我在angular 13中生成一个新组件后,我得到了以下错误。我删除了组件,但仍然得到相同的错误。
错误:
未捕获(承诺):空注入器错误:R3InjectorError(AppModule)[HttpService -〉ModuleSkillCollectionComponent -〉ModuleSkillCollectionComponent -〉ModuleSkillCollectionComponent]:空注入器错误:没有ModuleSkillCollectionComponent的提供程序!
当我向下滚动控制台时,我看到以下消息:

这让我想到:

<nav class="navbar max-w-full w-full mx-auto">
  <div class="flex-1">
    <div class="w-full top-0 border-b">
      <ul class="menu menu-horizontal w-screen">
        <li class="left-0 top-0 font-bold"><a href="">CompetentieApp</a></li>
        <li class="mr-10">
          <a routerLinkActive="tab-active" href="/faq">Eindniveaus</a>
        </li>
        <li class="mr-10"><a href="/faq">Overzicht Alle Modules</a></li>
        <li class="mr-10"><a href="/faq">Beheer</a></li>
        <li class="mr-10">
          <a routerLinkActive="tab-active" routerLink="moduleCompetenties">Logout</a>
        </li>
        <img
          class="absolute w-14 md:w-36 mr-10 right-0 top-0"
          src="assets/logo.png"
          alt="logo"
        />
      </ul>
    </div>
  </div>
</nav>
<router-outlet></router-outlet>

以下是我的app-routing.ts:

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'moduleCompetenties', component: ModuleSkillCollectionComponent },
  { path: '**', redirectTo: 'home', pathMatch: 'full' },
];

@NgModule({
  imports: [
      CommonModule,
      RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

更新

下面是http.service.ts

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

  // moduleSkillJson: ModuleSkillJSON[] = [];
  // private isGetting = false;

  constructor(private http: HttpClient, private moduleSKillClass: ModuleSkillCollectionComponent) {}

  post() {
    this.http.post('http://localhost:8080/add', this.postBody).subscribe(() => {
      console.log(this.postBody);
    });
  }

  getSkill(skillJson: Skill[]) {
    this.http.get<{[key: string] : Skill}>(environment.apiUrl + '/skillCollection')
        .pipe(
            map((res) => {
                  // console.log(res);
                  const skillDetailsArray: Skill[] = [];
                  for (const key in res) {
                    if (res.hasOwnProperty(key)) {
                      skillDetailsArray.push({...res[key], id: key})
                    }
                  }
                  // console.log(skillDetailsArray);
                  return skillDetailsArray;
                }
            )
        ).subscribe(skills => {
          // console.log(skills);
          skillJson = skills;
          // console.log("SkillDetails has " + this.skillJson.length + " entries.");
        }
    );
  }

  getModuleSkill(moduleSkillJson: ModuleSkillJSON[]) {
    this.http
        .get<{[key: string] : ModuleSkillJSON}>(environment.apiUrl + "/moduleSkill")
        .pipe(
            map((res) => {
              // console.log(res);
              const moduleSkill: ModuleSkillJSON[] = [];
              for (const key in res) {
                if (res.hasOwnProperty(key)) {
                  moduleSkill.push({...res[key], id: key})
                }
              }
              console.log(moduleSkill);
              return moduleSkill;
            })
        ).subscribe(moduleSkills => {
      moduleSkillJson = moduleSkills;
      this.moduleSKillClass.entriesLooper(moduleSkillJson);
    });
    // console.log("SkillDetails has " + this.moduleSkillJson.length + " entries.");
  }
}

下面是App.module.ts

@NgModule({
  declarations: [AppComponent, ModuleSkillCollectionComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
  ],
  providers: [HttpService],
  bootstrap: [AppComponent],
})
export class AppModule {}

下面是module-skill-collection.component.ts

export class ModuleSkillCollectionComponent implements OnInit {
  showTable: Boolean = false;
  loop: boolean = true;
  cohort: string = '22-23';
  moduleSkillJson: ModuleSkillJSON[];
  skillJson: Skill[] = [];
  entries: number[] = [];
  i: number = 1;

    constructor(private service: HttpService) {}

  ngOnInit(): void {
      this.getModuleSkills();
      this.getSkill();
  }

  isActive() {
    this.showTable = !this.showTable;
  }

    counter(i: number) {
        return new Array(i);
    }

    getSkill() {
        this.service.getSkill(this.skillJson);
    }

    getModuleSkills() {
        this.service.getModuleSkill(this.moduleSkillJson);
        this.entriesLooper(this.moduleSkillJson);
    }

    entriesLooper(moduleSKills: ModuleSkillJSON[]): number[] {
        for (let modulesSKill of moduleSKills) {
            this.entries.push(modulesSKill.entry);
        }
        return this.entries;
    }

}

export interface Skill {
    id?: string;
    skillGroupName: string;
    skillGroupType: string;
    skillDetailName: string;
    skillDetailType: string;
}

export interface ModuleSkillJSON {
    moduleCode: string;
    moduleName: string;
    skill: Array<Skill>[];
    entry: number;
    exist: number;
    id?: string;
}

有办法解决吗?

dffbzjpn

dffbzjpn1#

问题是类A(ModuleSkillCollection)正在类B(HttpService)的构造函数中初始化,类B正在类A的构造函数中初始化。

k3bvogb1

k3bvogb12#

我假设HttpServiceHttpClient的 Package 器-如果是这样,耶, Package 东西,快乐的日子。
错误表明这就是问题所在--服务不是provided的任何东西--无论是作为一个大的ol' singleton在app.module.ts中提供,还是在子模块中提供,也不是在组件本身中提供。

  • 在某个地方 *,必须有一个providers: [HttpService]线。

除此之外,我想知道它是否会误导,您正在向组件中注入ElementRef
怎么样例如,通常这些组件与@ViewChild()一起使用,除非您自己创建组件以便能够传入一个组件,否则应用程序从哪里获取此ElementRef以便注入它?
更新答案:
是的,你的组件被注入到你的服务中,你的服务被注入到你的组件中。
鱼与熊掌不可兼得。
除非……
HttpService

constructor(private readonly http: HttpClient) {}

public initComponent(component: ModuleSkillCollectionComponent): void {
    this._moduleSkillCollectionComponent = component;
}

ModuleSkillCollectionComponent

constructor(private readonly httpService: HttpService) {}

public ngOnInit(): void {
    this.httpService.initComponent(this);
}

相关问题