Reputation: 2441
I have created a class model for Schedules. I then import this class into my main program. My problem is that this class uses the HttpClient and the way I was taught to use it is to create the variable for it inside the constructor of the class. But the problem then comes in, when I create a new instance of the Schedule (newSchedule = new Schedule;) then it expects a parameter in the place of the HttpClient. How do I make it ignore the HttpClient when I want to create a new instance of the class?
Here is the Schedule model class:
import { HttpClient } from '@angular/common/http';
export class Schedule {
constructor(private httpClient: HttpClient) {}
}
But now I need to pass this.HttpClient in my main program, which of course is not needed:
import { HttpClient } from '@angular/common/http';
export class AppComponent {
constructor(private httpClient: HttpClient) {}
var NewSchedule = new Schedule(this.HttpClient);
}
How do I remove the need to pass this.HttpClient? I assume my process is quite wrong
Upvotes: 0
Views: 317
Reputation: 12960
After reading the comments, what I understood is, you want to have different instances of the Schedule
class but still want to access the httpClient
object.
Doing the following may be one solution:
Make a public method under the Schedule
class:
public getNewInstance(object: Object) {
let obj = Object.create(object.constructor.prototype);
object.constructor.apply(obj, [this.httpClient]);
return obj;
}
Also make your Subject
class injectable. Please note, Your class will be an injectable and an singleton inside another classes, but you will have a way to get several instances using that singleton
DO something like:
@Injectable()
export class Schedule ...
Then, In your appComponent, inject Subject
.
export class AppComponent {
constructor(private subjectInstance: Subject) {}
...
private newSubjectInstance;
ngOnInit() {
this.newSubjectInstance = this.subjectInstance.getNewInstance(this.subjectInstance);
// so this should be a new instance but still have the httpClent inside it.
}
Upvotes: 0
Reputation:
Your process seems indeed wrong. But you ask for help, so we provide.
You need to make the parameter of the constructor optional. Do like so :
export class Schedule {
constructor(private http?: HttpClient){}
}
You can also give it a default value :
export class Schedule {
constructor(private http: HttpClient = null){}
}
Upvotes: 3