Moshe Kohavi
Moshe Kohavi

Reputation: 457

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?

Upvotes: 0

Views: 48

Answers (2)

Abhishek Gangwar
Abhishek Gangwar

Reputation: 2408

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()

Upvotes: 1

dev_in_progress
dev_in_progress

Reputation: 2494

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

Upvotes: 0

Related Questions