[英]Angular 5 Understanding External Class Imports
我為時間表創建了一個類模型。 然后,將此類導入到我的主程序中。 我的問題是,此類使用HttpClient,而有人教我使用它的方法是在該類的構造函數中為其創建變量。 但是問題來了,當我創建Schedule的新實例(newSchedule = new Schedule;)時,它期望在HttpClient處放置一個參數。 當我要創建類的新實例時,如何使它忽略HttpClient?
這是Schedule模型類:
import { HttpClient } from '@angular/common/http';
export class Schedule {
constructor(private httpClient: HttpClient) {}
}
但是現在我需要在我的主程序中傳遞this.HttpClient,當然不需要:
import { HttpClient } from '@angular/common/http';
export class AppComponent {
constructor(private httpClient: HttpClient) {}
var NewSchedule = new Schedule(this.HttpClient);
}
如何消除傳遞this.HttpClient的需要? 我認為我的過程很錯
您的過程似乎確實是錯誤的。 但是您需要幫助,所以我們提供了。
您需要使構造函數的參數為可選。 這樣做:
export class Schedule {
constructor(private http?: HttpClient){}
}
您也可以給它一個默認值:
export class Schedule {
constructor(private http: HttpClient = null){}
}
閱讀注釋后,據我了解,您希望擁有Schedule
類的不同實例,但仍想訪問httpClient
對象。
執行以下操作可能是一種解決方案:
在Schedule
類下創建一個公共方法:
public getNewInstance(object: Object) {
let obj = Object.create(object.constructor.prototype);
object.constructor.apply(obj, [this.httpClient]);
return obj;
}
同時使您的Subject
類可注射。 請注意,您的課程將是可注入的,並且是另一個課程中的一個單例,但是您將可以使用該單例來獲取多個實例
做類似的事情:
@Injectable()
export class Schedule ...
然后,在您的appComponent中,注入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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.