Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/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
Javascript 在角度组件中创建角度服务时,如何为其设置自定义构造函数参数?_Javascript_Angular_Typescript_Ecmascript 6 - Fatal编程技术网

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

Javascript 在角度组件中创建角度服务时,如何为其设置自定义构造函数参数?,javascript,angular,typescript,ecmascript-6,Javascript,Angular,Typescript,Ecmascript 6,我正在将Typescript类更改为Angular 6服务: export class TestClass { customParam1; customParam2; constructor(customParam1, custom1Param2) { this.customParam1 = customParam1; this.customParam2 = customParam2; } } 对服务: @Injectable

我正在将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;
    }
} 
在一个示例中创建第一个代码块时,调用新的TestClass(“一”、“二”)


在组件中,创建服务时如何设置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';
否则,您将不得不创建一个新的服务实例,但这将违背单例的目的


最好的办法是告诉我们你想要实现什么,这样我们才能为你找到最好的解决方案

您可以为静态值提供注入令牌,但通常的想法是您不会这样做。依赖项注入的目的是自动解析构造函数参数。@bryan60您能给出一个小的代码示例或一个如何实现这一点的链接吗?