我应该在注入的 Angular 服务上使用只读而不是将它们公开吗?
我今天讨论了一些同事说他们像这样注入他们的 Angular 服务:
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 是 Angular 的基础部分.如果真的有人这样做了,这个人是最好跑到这个坑里失败还是完全做不到
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
在这种情况下,对于开始学习 Angular 和 TypeScript 的人来说,理解起来可能非常复杂,原因有几个
readonly
in this situation might be pretty complex to understand for someone who starts learning Angular and TypeScript for a couple of reasons
- Angular 在他们的任何官方 DI 文档中都没有使用这种方法
- 你需要知道
readonly
是如何工作的,它只保护我注入的服务的引用,而不保护任何属性
- 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
你怎么看?有没有我可能没见过的官方参考资料?当我尝试使用谷歌搜索 readonly
在 Angular 概念
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
最后一句话:虽然 100% 正确 - 可以操纵 public service: Service
的引用 - 我仍然不确定是否应该解决这个问题做与不做.
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.
这不是您必须要做的事情,但是将它们设为 readonly
是一种很好的做法,因为您可能不想要再次重新分配实例.
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.