【问题标题】:Angular 6: provide func in new class constructorAngular 6:在新的类构造函数中提供 func
【发布时间】:2019-02-28 08:38:08
【问题描述】:

如果它与某人的问题重复,我很抱歉。但是我找不到我的问题的解决方案。

我有一个 Angular 6 应用程序。我做了一个服务(不可注入)。

我需要创建一个新的服务实例,然后在里面做一些魔法,然后在外面调用函数。但是当我将一个值返回给组件的函数时,我看不到组件的变量。下面是代码示例:

example.component.ts

import { Calculation } from './calculation.service';

export class ExampleComponent implements OnInit {
    test: 1;
    potatoes: 2
    calculation: Calculation;

    ngOnInit() {
        this.calculation = new Calculation(this.doExternalMagic, this.potatoes)
    }

    doExternalMagic(potatoes: number) {
        console.log(potatoes);  // 3
        console.log(this.test); // undefined
    }
}

calculation.service.ts

export class Calculation {
    // i'm not sure that doExternalMagic should have type of Function
    constructor(private doExternalMagic: Function, private potatoes: number) { }

    public init() {
        this.potatoes = this.potatoes + 1;
        this.doExternalMagic(this.potatoes);
    }

}

我还尝试在Calculation 构造函数中将doExternalMagic 设为公开,但结果是相同的。当我在服务中提供我的功能时,似乎我做错了什么。如何正确提供它以在组件外部制造魔法?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    将您的函数作为箭头函数传递:

    ngOnInit() {
        this.calculation = new Calculation((potatoes) => this.doExternalMagic(potatoes), this.potatoes)
    }
    

    或使用bind()。问题在于this 关键字上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2021-09-19
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多