Imagine you are working with Angular and have the following custom libraries:
The first library is a base service library:
// base.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export abstract class BaseService {
constructor(private httpClient: HttpClient) {}
protected request(): Observable<any> {
return this.httpClient.request('GET', 'http://127.0.0.1:3100/CRM/v1/customers');
}
}
The second custom library is:
// test.service.ts
import { Injectable } from '@angular/core';
import { BaseService } from '@company/data-access-base';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export abstract class TestService extends BaseService {
testRequest(): Observable<any> {
return this.request();
}
}
Then you decide to incorporate the TestService into your application.
Assuming you have already imported HttpClientModule
in the app.module.ts file of your application, you proceed to inject the TestService and utilize it in the following manner:
import { Component, OnInit } from '@angular/core';
import { TestService } from '@company/data-access-test';
@Component({
selector: 'comp-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
constructor(private testService: TestService) {}
ngOnInit() {
this.testService.testRequest().subscribe((r) => console.log('Test ok', r))
}
}
However, upon testing the functionality, an error is encountered in the console:
core.js:4610 ERROR TypeError: Cannot read property 'request' of undefined
at TestService.request (company-data-access-base.js:42)
at TestService.testRequest (company-data-access-crm.js:7)
at HomeComponent.ngOnInit (home.component.ts:13)
at callHook (core.js:3405)
...
The question then arises: How can I ensure that HttpClient is properly injected into the BaseService?