0

I would like to know if we need to put readonly when i inject something in the constructor ? For example :

constructor(readonly private userService: UserService) { }

Can you explain the usefulness (or not) of this practice ?

Tim
  • 162
  • 2
  • 10
  • Does this answer your question? [Should I use readonly on injected Angular services instead of making them public?](https://stackoverflow.com/questions/54871856/should-i-use-readonly-on-injected-angular-services-instead-of-making-them-public) – Smokey Dawson Mar 23 '20 at 23:25

2 Answers2

5

Short: Ususally you don't need readonly in DI since you deal with injected services and typesafety protects you from assigning new values.

Details: First of all, if you want to use private and readonly, it's

private readonly userService: UserService

So readonly comes after private.

Then note the difference between public/private/protected and readonly.

The public/private/protected are about visibility.

  • public: Anybody can see this variable
  • private: Variable is only visible inside of the class where you define this
  • protected: Only visible inside and derived classes (A extends B)

Readonly on the other hand is about if you want somebody to NOT being able to change it.

Simple example:

private amountOfPizzas = 1;
private readonly stomachSize = 2;

public eat(numberOfPizzas: number): void {
    if(this.stomachSize < numberOfPizzas) {
        this.stomachSize = numberOfPizzas; // will throw an error
    }
    this.amountOfPizzas = numberOfPizzas;  // works
    eat(); // ..
}

This also applies to 100% to dependency injection.

When you inject a Service in the manner of private userService: UserService, then this variable can be changed. However, due to Typescript it can only be assigned a new UserService instance so it doesn't really make much of a difference if you put readonly or not.

However let's say you would inject another token like:

constructor(private numberOfPizzas: number) {}

Then it's not really a service that is being injected and I wonder if this actually would work. But let's just assume it does .. or for any reason, the compiler doesn't find the error, then inside the class we could assign it a new value. And this is very likely not what you really want. Bad.

More dangerous would be if you use public visibility, then of course, there would be more places being able to change this variable - and hence it would be harder to identify where a problem comes from.

hogan
  • 1,434
  • 1
  • 15
  • 32
1

The readonly doesn't actually make it readonly It just means that Typescript will not let anyone external change it private should accomplish the same thing I think that the private service: Service is best way or use public service : Service to use it in html template