H. Motsu
H. Motsu

Reputation: 117

Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule) Angular 13

After I generated a new component in angular 13, I am getting the following error. I deleted the component, but I still get the same error.

The error:

Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[HttpService -> ModuleSkillCollectionComponent -> ModuleSkillCollectionComponent -> ModuleSkillCollectionComponent]: NullInjectorError: No provider for ModuleSkillCollectionComponent!

When I scroll down the console, I come across the following message:

error reference

And this takes me to:

code

<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>

Here is my 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 {}

UPDATE

Here is the 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.");
  }
}

Here is the App.module.ts:

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

Here is the 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;
}

Any idea how to solve it?

Upvotes: 1

Views: 6955

Answers (2)

Krenom
Krenom

Reputation: 2118

I assume HttpService is a wrapper around HttpClient - if so, yay, wrapping things, happy days.

The error suggests that's the issue - that service isn't being provided by anything - either as a big ol' singleton by being provided in the app.module.ts, nor in a sub module nor in the component itself.

Somewhere, there has to be a providers: [HttpService] line.

Outside of that, and I wonder if it's misleading, you're injecting an ElementRef into the component?

How's that working? Typically those are used with @ViewChild() for example, and unless you're creating the components yourself to be able to pass one in, where is the app getting this ElementRef from in order to inject it?


Updated answer:

Yeah, you have your component being injected into your service, and your service being injected into your component.

Can't have your cake an eat it too.

.... Unless....

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);
}

Upvotes: 0

H. Motsu
H. Motsu

Reputation: 117

The Issue is that class A (ModuleSkillCollection) is being initialized in the constructor of class B (HttpService) and Class B is being initialized in the constructor of class A.

Upvotes: 0

Related Questions