Yoojasung
Yoojasung

Reputation: 33

what is different use private vs public keyword in angular2 constructor()

I am starting to learn angular v2 and ionic v2.

In the ng2 hero tutorial they use a private keyword in constructor but in the ionic boilerplate source they use a public keyword in constructor.

angular2 tutorial

heroes: Hero[];

constructor(
     private heroS: HeroService,
     private router: Router
) { }

ngOnInit() { 
    this.heroS.getHeroes().then(heroes => {
        this.heroes = heroes;
    })
}

ionic tutorial

constructor(public navCtrl: NavController, public navParams: NavParams) {
}

After trans compile to es5, public and private is the same in .js file. but I really don't understand what the difference is.

Upvotes: 3

Views: 3091

Answers (3)

Sathya Narayanan
Sathya Narayanan

Reputation: 11

This is the feature of "Parameter Properties" of typescript. When we use any keyword Public,Private,Protected or readonly, it automatically creates and initializes the class property. Please check https://medium.com/@daveford/parameter-properties-in-typescript-c99df6ba13f7

Upvotes: 1

Chris Skura
Chris Skura

Reputation: 161

private and public only apply at compile time and not run time. Functions are public by default and tagging something as "private" is simply announcing your intent to keep it private.

Upvotes: 0

Yoni Rabinovitch
Yoni Rabinovitch

Reputation: 5261

I believe the Ionic boilerplate code uses public members in constirctors in order to be able to take advantage of Ahead of Time (AoT) Compilation. See Angular 2 Ahead-of-Time compiler: must I make all class properties public? .

Upvotes: 1

Related Questions