Suppose you have the following Angular libraries:
First library, 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');
}
}
Second library:
// 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();
}
}
Than you decide to use the TestService in your app.
Off course, you already imported HttpClientModule
in the app.module.ts of your app. Then you inject TestService and try to use it:
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))
}
}
Here you get the following error in your 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)
...
How to I get HttpClient injected in the BaseService?
Turns our that, given the fact that the injected service in the application is TestService
, that's the service that Angular (and as far as I know any other framework's DI system) will manage.
So, easy solution, simply add a constructor to each of the services, and call the super.(httpService).
// 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 {
// that's what was missing
constructor(protected httpClient: HttpClient) {
super(httpClient);
}
testRequest(): Observable<any> {
return this.request();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.