Search code examples
angularfunctiondependency-injectionundefined

Angular undefined functions after DI


I'm trying to inject a class (currently a mocking) in my component FirstComponent For some reasons, my functions in my CourseServiceMock are undefined eventhough I've declared them here :

CourseServiceMock.ts

import {Course} from "../data/Course";
import {Injectable} from "@angular/core";
import {CourseService} from "./CourseService";

@Injectable()
export class CourseServiceMock extends CourseService{

  constructor() {
    super();
  }

  public get(i: number): Course {
    return new Course("IDID",9,12,"test",i);
  }

  public getAll(): Course[]{
    return [
      new Course("IDID",9,12,"test",1),
      new Course("IDID",9,12,"test",2),
      new Course("IDID",9,12,"test",3),
      new Course("IDID",9,12,"test",4),
    ];
  }
}

CourseService.ts

import {ICourseService} from "./ICourseService";
import {Course} from "../data/Course";

export abstract class CourseService implements ICourseService{
  public courses:Course[] | undefined;

  public abstract get(i: number): Course;
  public abstract getAll(): Course[];

  protected constructor() {
    this.courses = [];
  }
}

ICourseService.ts

import {Course} from "../data/Course";

export interface ICourseService{
  getAll():Course[];
  get(i:number): Course;
}

app.module.ts where I declare my data to inject

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';
import {CourseServiceMock} from "./services/CourseServiceMock";
import {CourseService} from "./services/CourseService";

@NgModule({
  declarations: [
    AppComponent,
    FirstComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: CourseService,useValue:CourseServiceMock}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

first.component.ts where my service is injected

import {Component, Injectable, OnInit} from '@angular/core';
import {Course} from "../data/Course";
import {CourseService} from "../services/CourseService";

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.scss'],
})
@Injectable()
export class FirstComponent implements OnInit {

  courseService:CourseService;
  maListe: Course[] | undefined;

  constructor(courseService:CourseService) {
    this.maListe = undefined;
    this.courseService = courseService;
    console.log(this.courseService);
  }

  ngOnInit(): void {
    this.maListe = this.courseService.getAll();
    console.log(this.maListe);
  }

}

console screenshot


Solution

  • I had been using useValue instead of useClass in my app.modules.ts.

    Still keeping the thread in case someone would face the same issue.