I manage a factory provider service that selects a service based on a flag. Everything works fine when I need a debug students service, but when I set the flag to false, the application throws an ERROR TypeError: serverService.fetchData is not a function. How can this be resolved?
Students.provider
import { StudentDebugService } from "./student-debug.service";
import { StudentService } from "./student.service";
import { ServerService } from "./server.service";
const isNeedDebug: boolean = false;
const studentServiceFactory = (studentDebugService: StudentDebugService, serverService: ServerService) => {
if (isNeedDebug) {
return new StudentService(studentDebugService.students);
}
serverService.fetchData().subscribe( (students) => {
return new StudentService(students);
});
};
export let studentServiceProvider = {
provide: StudentService,
useFactory: studentServiceFactory,
deps: [ServerService, StudentDebugService]
};
StudentsService
import { Inject, Injectable } from "@angular/core";
export interface StudentsArgs {
id: number;
surName: string;
name: string;
middleName: string;
birthday: string;
averageRate: number;
}
@Injectable({providedIn: "root"})
export class StudentService {
constructor(@Inject(StudentService)public students: StudentsArgs[]) {
}
getStudents(): StudentsArgs[] {
return this.students;
}
}
ServerService
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({providedIn: "root"})
export class ServerService {
constructor(private http: HttpClient) {
}
fetchData(): Observable<any> {
return this.http.get("http://localhost:3000/api");
}
}
The StudentsProvider component should inject the necessary service in app.component.constructor
App.Component.ts
import {ChangeDetectionStrategy, Component, Inject, OnInit} from '@angular/core';
import { StudentsArgs, StudentService } from "./services/student.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit {
students: StudentsArgs[] = [];
constructor(private studentService: StudentService) {
}
ngOnInit(): void {
console.log(this.studentService);
this.students = this.studentService.students;
}
App.module.ts
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { HttpClientModule } from "@angular/common/http";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { studentServiceProvider } from "./services/student.service.provider";
import {ServerService} from './services/server.service';
import {StudentDebugService} from './services/student-debug.service';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
],
providers: [studentServiceProvider],
bootstrap: [AppComponent]
})
export class AppModule { }