我正在将 Typescript 类更改为 Angular 6 服务:
export class TestClass {
customParam1;
customParam2;
constructor(customParam1, custom1Param2) {
this.customParam1 = customParam1;
this.customParam2 = customParam2;
}
}
至服务:
@Injectable({
providedIn: 'root'
})
export class TestClassService {
customParam1;
customParam2;
constructor(customParam1, custom1Param2) {
this.customParam1 = customParam1;
this.customParam2 = customParam2;
}
}
在 Angular 中创建第一个代码块时,您可以调用 new TestClass("one", "two")。
在组件中,创建服务时如何设置customParam1和customParam2?
最佳答案
如果你不知道,
constructor(customParam1, custom1Param2) {
this.customParam1 = customParam1;
this.customParam2 = customParam2;
}
是长版本
constructor(private customParam1, private custom1Param2) {}
现在,对于你的问题:由于你在根级别提供服务,它将产生一个单例:因为服务是其他功能(例如组件)的依赖项,所以它们将首先加载(或者它们的实例将被转发,但最终目标是相同的)。
如果您想在服务中设置值,则必须使用 setter :函数或实际 setter 。
setCustomParam1(value) { this.customParam1 = value; }
set setCustomParam2(value) { this.customParam2 = value; }
this.setCustomParam1('your value');
this.setCustomParam2 = 'your value';
否则,您将不得不创建一个新的服务实例,但这将违背单例的目的。
最好告诉我们您想要实现什么目标,以便我们为您找到最佳解决方案。
关于javascript - 在 Angular 组件中创建 Angular 服务时,如何为其设置自定义构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52369131/