Reputation: 758
I am changing a Typescript class to an Angular 6 service:
export class TestClass {
customParam1;
customParam2;
constructor(customParam1, custom1Param2) {
this.customParam1 = customParam1;
this.customParam2 = customParam2;
}
}
To the service:
@Injectable({
providedIn: 'root'
})
export class TestClassService {
customParam1;
customParam2;
constructor(customParam1, custom1Param2) {
this.customParam1 = customParam1;
this.customParam2 = customParam2;
}
}
When creating the first code block in an Angular, you call new TestClass("one", "two").
In the component, how do I set customParam1 and customParam2 when creating the service?
Upvotes: 0
Views: 993
Reputation:
In case you did not know,
constructor(customParam1, custom1Param2) {
this.customParam1 = customParam1;
this.customParam2 = customParam2;
}
Is the long version of
constructor(private customParam1, private custom1Param2) {}
Now, for your question : since you provide your service at root level, it will produce a singleton : because services are dependencies of other features (such as components), they will be loaded first (or their instance will be forwarded, but the end goal is the same).
If you want to set values into your service, you will have to use setters : either functions or actual setters.
setCustomParam1(value) { this.customParam1 = value; }
set setCustomParam2(value) { this.customParam2 = value; }
this.setCustomParam1('your value');
this.setCustomParam2 = 'your value';
Otherwise, you will have to create a new instance of your service, but that would defeat the purpose of singletons.
The best would be to tell us what are you trying to achieve, so that we can find the best solution for you.
Upvotes: 1