I had a discussion today where some of my colleagues said that they inject their Angular services like that:
constructor(readonly language: I18nService)
They said they do this because it prevents consumers of my component to change the injected service, kinda like that:
@Component({ ... })
class ComponentA {
constructor(public language: I18nService) {}
}
@Component({ ... })
class ComponentB {
@ViewChild(ComponentA) compA: ComponentA;
constructor() {
this.compA.language = new I18nService();
}
}
So, while technically they are right I'm still not convinced that I should do it that way. I ask myself the following question:
DI is a fundamental part of Angular. If someone really does this, should this person better run into this pit and fail or should he/she not be able to do this at all
readonly in this situation might be pretty complex to understand for someone who starts learning Angular and TypeScript for a couple of reasons
readonly works and that it just protects the reference of my injected service but none of the propertiesIn my opinion, it is a corner case problem, even though there's a simple solution to it
What do you think? Are there any official references I might not have seen? I haven't found anything when I tried to google for the usage of readonly in Angular concepts
One last word: While it is 100% true - It is possible to manipulate a reference of public service: Service - I'm still not sure if this should be solved at all and struggle whether to do it or not.
It is not something that you have to do, but it is good practice to make them readonly since you probably don't want to reassign the instance again.
Read-only properties may have initializers and may be assigned to in constructors within the same class declaration, but otherwise, assignments to read-only properties are disallowed.
you can add private readonly service : ServiceClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With