Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在ionic中如何在类中使用提供程序_Angular_Ionic Framework_Service_Instance_Provider - Fatal编程技术网

Angular 在ionic中如何在类中使用提供程序

Angular 在ionic中如何在类中使用提供程序,angular,ionic-framework,service,instance,provider,Angular,Ionic Framework,Service,Instance,Provider,我创建了一个类而不是组件,我希望它使用来自提供者MyService的数据。例: export class MyClass { arg1 : Number; constructor(arg : Number, private myService : MyService) { this.arg1 = arg; } calc() { console.log(this.arg + this.myService.arg2); } } 现在,我想创建这个类的新实例:

我创建了一个类而不是组件,我希望它使用来自提供者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);
但我少了一个论点。。。
如何创建具有提供程序的类的实例?可能吗?或者我没有很好地使用它?

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

您必须在构造函数中提供对服务的引用

假设您试图在另一个类中创建您的类的实例, 所以你必须定义这样的东西

你原来的班级

在其中创建新实例的类

现在你可以使用这样的引用-

a.calc()
这个参数是私有的,myService:myService是在提供者构造函数中定义的
export class AnotherClass {
   constructor(public myService: Myservice){
    let a : MyClass = new MyClass(7,myService);
   }
}
a.calc()