4

Why to use private access specifier only to instantiate the providers in constructor ? Is there any specific reason to use private access specifiers only ?

Private injection

constructor(private service: InjectedService)

Public injection

constructor(service: InjectedService)
Nicolas Henneaux
  • 11,507
  • 11
  • 57
  • 82
Rajni
  • 95
  • 1
  • 8
  • This doesn't mean much to me. Could you illustrate what you're asking with example code? I guess what you mean by "instantiate the providers" is "inject the services". And I guess you should rather ask yourself: why should they be public? – JB Nizet Aug 29 '16 at 11:00
  • Yes, I mean injecting service. ex: constructor(private userSer: UserService){}; Am not able to see any difference with public and private in this case. Then my doubt is why to prefer private access specifier – Rajni Aug 29 '16 at 11:05
  • @JBNizet answer should be marked as correct. My summary: if there is no reason for it to be `public`, mark it `private`. – Martin Aug 29 '16 at 11:57

3 Answers3

7

Using private acts a shorthand, instead of doing:

constructor(service: InjectedService) {
   this.service = service
}

you can:

constructor(private service: InjectedService) {}
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
6

The difference is that private makes the field private, i.e. not accessible from the outside TypeScript code.

Since TypeScript is compiled to JavaScript, and JavaScript doesn't have the notion of private fields, it's still accessible from the outside, including the view, but making it private is still a good idea because it documents the fact that the service is... private to the class, and should thus not be used outside of the class itself, including the view. BTW, I think that the offline compiler that Angular will soon provide to compile the templates to JavaScript code will refuse to compile the views if they use private fields.

In general, in OO, private should be the default for fields: you want to expose as few fields as possible, to be able to refactor the implementation of your class and change its internals without breaking the external code using that class, and relying only on the public API.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

1) Private injection

constructor(private service: InjectedService)

service is a parameter but also becomes a property of your object, so you will be able to access it via this.service in other methods of you class

2) Public injection

constructor(service: InjectedService)

service is only a parameter in the constructor's scope, and won't be assoiciated with the object anymore, so you won't be able to do this.service

Val Martinez
  • 617
  • 6
  • 15