javascript - 在 Angular 组件中创建 Angular 服务时,如何为其设置自定义构造函数参数?

标签 javascript angular typescript ecmascript-6

我正在将 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/

相关文章:

indexing - Angular2 *ngFor 将索引设置为同一标签内的属性

css - 如果数据内容未完全显示,则使覆盖 div(如引导模式或 Angular 对话框)垂直滚动

typescript - 更干净的功能重载,无需复制不改变的部分

angular - 如何在 Angular 2 中绑定(bind) HTML 中组件的静态变量?

javascript - jQuery load() 失败,但没有 JS 错误

Angular CLI 为已经存在的组件创建 .spec 文件

javascript - 单击时触发 JavaScript 操作?

typescript - 有没有办法从不同长度的元组的联合中提取带有类型的最后一个元素?

javascript - 我如何将类与js中的字符串进行比较

javascript - 具有相同网址的多个“赞”按钮