问题
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- Angular doesn't use this approach in any of their official DI docs
- You need to know how
readonly
works and that it just protects the reference of my injected service but none of the properties
In 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.
回答1:
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.
回答2:
you can add private readonly service : ServiceClass
来源:https://stackoverflow.com/questions/54871856/should-i-use-readonly-on-injected-angular-services-instead-of-making-them-public