Just to continue with my custom class in Angular 2/4 that I've started at: methods in angular typescript class are null after http get , now I want to go one step beyond.
This is my custom original class:
export class Book{
id: number,
title: string;
author: string;
read: integer;
author: string;
constructor() {
}
public incRead(times: integer){
this.read = this.read + times;
}
}
To consume this class from components I use it this way:
this._httpClient.Get<Book[]>(url).subscribe().map(
(books: Book[]) => {
const tempbooks = new Array<Book>();
books.forEach(book => {
tempbooks.push(Object.assign(new Book(),book);
}
return tempbooks;
}
)
As in HttpClient not running constructor, and this way I can call the incRead method from the component.
Now I would like to add a "post" method, something like this:
export class Book{
id: number
title: string;
author: string;
read: integer;
author: string;
private httpClient: HttpClient;
constructor() {
}
public incRead(times: integer){
this.read = this.read + times;
}
public post(): Observable(boolean)
return this.httpClient.post<boolean>(url + Book.id.toString());
}
But I can't get a way to inject HttpClient service. I've tried with
const injector = ReflectiveInjector.resoveAndCreate([HttpClient]);
this.httpClient = injector.get(HttpClient)
in the constructor but I get an error about the Backend parameter at the injector get method that is necessary to create the HttpClient instance.
I have been trying diferent options
creating external service to inject the HttpClient (as in Get angular 2 service inside a custom class instantiated by me) but I get the same error as with the ReflectiveInjector solution.
Pass the service from the component as a parameter to the constructor, but it's not compatible with the Object.assign(new Book(), book).
Maybe I'm using a bad approach to create a custom classes in Angular (based on in my OOP past developments) and there is some other way to detach classes from components that I'm missing.
Please be kind, I've done my homework and didn't find anything that gets me in the correct direction without "hairy" code.