简体   繁体   中英

Angular 5 Understanding External Class Imports

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

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){}
}

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.
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM