[英]How to use provider in class in ionic
我創建了一個類(不是組件),並且希望它使用提供程序(MyService)中的數據。 例如:
export class MyClass {
arg1 : Number;
constructor(arg : Number, private myService : MyService) {
this.arg1 = arg;
}
calc() {
console.log(this.arg + this.myService.arg2);
}
}
現在,我想創建此類的新實例:
let a : MyClass = new MyClass(7);
但是我缺少1個參數...如何創建具有提供程序的類的實例? 可能嗎? 還是我沒有很好地使用它?
您必須在構造函數中提供對服務的引用。
假設您試圖在另一個類中創建該類的實例,那么您必須定義類似這樣的內容。
您的原始班級
export class MyClass {
arg1 : Number;
myservice: MyService;
constructor(arg : Number, private myService : MyService) {
this.arg1 = arg;
this.myservice = myService;
}
calc() {
console.log(this.arg + this.myService.arg2);
}
}
您要在其中創建新實例的類
export class AnotherClass {
constructor(public myService: Myservice){
let a : MyClass = new MyClass(7,myService);
}
}
現在,您可以使用像這樣的引用-
a.calc()
假設您在某些組件中調用MyClass:MyComponent。
在該組件中,您可以使用構造函數來注入服務MyService,在構造函數中或您希望使用參數的任何地方,都可以使用參數初始化MyClass,例如:
@Component({})
export class MyComponent{
constructor(public myService: MyService){
let a: MyClass = new MyClass(7, this.myService);
}
}
或者如果您想在構造函數之外調用它:
@Component({})
export class MyComponent{
let a: MyClass;
constructor(public myService: MyService){
this.a = new MyClass(7, this.myService);
}
someMethod(): void {
this.a.calc();
}
}
並且,在您的類中,將變量分配給傳遞的參數myService:
export class MyClass {
arg1 : Number;
myService: MyService;
constructor(arg : Number, private myService : MyService) {
this.arg1 = arg;
this.myService = myService;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.