【发布时间】: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