【问题标题】:How to use provider in class in ionic如何在 ionic 类中使用提供者
【发布时间】:2018-07-12 10:16:24
【问题描述】:

我创建了一个类(不是组件),我希望它使用来自提供者 (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 个参数... 如何创建具有提供者的类的实例?可能吗?还是我没用好?

【问题讨论】:

  • 那个参数是private that myService : MyService 这是在你的提供者构造函数中定义的

标签: angular ionic-framework service instance provider


【解决方案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()

【讨论】:

    【解决方案2】:

    假设您在某个组件中调用 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;
        }
    

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 2019-12-08
      • 2017-12-28
      • 2019-03-29
      • 2020-01-06
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2018-07-21
      相关资源
      最近更新 更多