Should I use readonly on injected Angular services instead of making them public?

旧城冷巷雨未停 提交于 2021-02-09 11:45:49

问题


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:

  1. 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

  2. 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
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!