简体   繁体   English

如何在离子课上使用提供者

[英]How to use provider in class in ionic

I created a class (not component) and I want it to use data from a provider (MyService). 我创建了一个类(不是组件),并且希望它使用提供程序(MyService)中的数据。 ex: 例如:

export class MyClass {
  arg1 : Number;

  constructor(arg : Number, private myService : MyService) {
    this.arg1 = arg;
  }

  calc() {
    console.log(this.arg + this.myService.arg2);
  }
}

Now, I want to create new instance of this class: 现在,我想创建此类的新实例:

let a : MyClass = new MyClass(7);

but I have 1 argument missing... How can I create instances of class that has provider(s)? 但是我缺少1个参数...如何创建具有提供程序的类的实例? Is it possible? 可能吗? or maybe I'm not using it well? 还是我没有很好地使用它?

You have to Provide the reference to your service in your constructor. 您必须在构造函数中提供对服务的引用。

Suppose you are trying to create the instance of your class in another class, So you have to define something like this. 假设您试图在另一个类中创建该类的实例,那么您必须定义类似这样的内容。

Your Original class 您的原始班级

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

Class in which you are creating the new instance 您要在其中创建新实例的类

export class AnotherClass {
   constructor(public myService: Myservice){
    let a : MyClass = new MyClass(7,myService);
   }
}

Now you can use the reference like this - 现在,您可以使用像这样的引用-

a.calc()

Lets say you are calling MyClass in some component: MyComponent. 假设您在某些组件中调用MyClass:MyComponent。

In that component you have constructor that injects service MyService, in constructor or wherever you want you can initialize MyClass with parameters, for example: 在该组件中,您可以使用构造函数来注入服务MyService,在构造函数中或您希望使用参数的任何地方,都可以使用参数初始化MyClass,例如:

@Component({})
export class MyComponent{
    constructor(public myService: MyService){
        let a: MyClass = new MyClass(7, this.myService);
    }
}

or if you want to call it outside of constructor: 或者如果您想在构造函数之外调用它:

@Component({})
export class MyComponent{

    let a: MyClass;

    constructor(public myService: MyService){
        this.a = new MyClass(7, this.myService);
    }

    someMethod(): void {
        this.a.calc();
    }

}

and also, in your class assign variable to passed parameter myService: 并且,在您的类中,将变量分配给传递的参数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.

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