Hi everyone, i'm new with Angular and I am having troubles with Injectable classes.
I have an abstract class (on web.ts) which one of its protected attributes is an HttpClient object. The definition of this abstract class is as follows:
import { HttpClient } from "@angular/common/http";
export abstract class Web {
protected baseURL: string;
constructor(baseURL: string, protected http: HttpClient) {
this.baseURL = baseURL;
}
public abstract RetrieveData(pattern: string);
}
Then I have another class (on webA.ts) which extends the Web class:
import { Web } from './web';
export class WebA extends Web {
constructor() {
super("https://www.test.com");
}
private Search(pattern: string) {
pattern = pattern.replace(" ", "+");
var searchURL = this.baseURL + `/site/searchpage.jsp?st=${pattern}&id=pcat17071`;
console.log(searchURL);
this.http.get(searchURL).subscribe(data => {
console.log(data);
});
}
public RetrieveData(pattern: string) {
this.Search(pattern);
}
}
Finally, in a class of a component for my website I want to instantiate WebA as:
private webA: Web = new WebA();
It tells me that I need to pass an HttpClient object on super("https://www.test.com");
in webA.ts. To fix it, I can make the constructor for WebA like:
constructor(@Inject(HttpClient) http: HttpClient) {
super("https://www.test.com", http);
}
But this would lead me to do private webA: Web = new WebA(this.http);
forcing me to have on my component class:
import { HttpClient } from "@angular/common/http";
...
constructor(private http: HttpClient) {}
I know there must be another way to do it because in my opinion this is breaking hierarchy on my classes
TL;DR:
I need to "auto-inject" an HttpClient on an abstract class to not to need passing this object as an argument on super in the extender class.