Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use 'readonly' keyword during service initialization in constructor?

In Angular 2+ combined with Type Script is it necessary to use readonly keyword when we initialize services in the component constructor?

What is the purpose to do so?

export class MyComponent {

    constructor(private readonly http: HttpClient) {}

}
like image 843
Alex Link Avatar asked Oct 25 '25 09:10

Alex Link


2 Answers

It is not required, however it is good practice since you probably don't want to reassign to the http property later on.

See the Typescript doc for more details:

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.

like image 50
jo_va Avatar answered Oct 27 '25 22:10

jo_va


No, it's not necessary to use the readonly keyword such usage is not mentioned in angular docs and not used in practice

like image 38
Sathiraumesh Avatar answered Oct 28 '25 00:10

Sathiraumesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!