简体   繁体   中英

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). 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)? 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.

In that component you have constructor that injects service MyService, in constructor or wherever you want you can initialize MyClass with parameters, for example:

@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:

export class MyClass {
    arg1 : Number;
    myService: MyService;

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

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