Syntax of member properties and constructors in angular 2 typescript

So I’m looking at an ionic 2 project which is using Angular 2 and Typescript and am a bit confused about how member properties are set. Looking at the example below, Angular automatically injects the dependencies in the constructor arguments. In the case of nav, we are explicitly setting the instance member nav to what’s being passed in by the constructor. In the case of Firebase auth, we don’t explicitly set it to a member variable, but we can still access it via this.auth in the login method, how come? if we try the same thing with this.nav it won’t work unless we explicitly set the instance variable. What does using the private keyword do in the constructor parameters do – is it redundant to declare a private keyword in the property definition in the class and also in the function parameters? Is it magically binding constructor variables to class properties if they have the same name?

export class LoginPage {
  private auth: FirebaseAuth;

  constructor(nav:NavController, private auth: FirebaseAuth) {
    this.nav = nav; // if we don't do this, the setRoot below in login doesn't do anything
    //this.auth = auth;  // how come we don't have to set the member variable here and it's still available in the login method

  login() {
    this.auth.login().then(authData =>{

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

Notice private keyword in private auth: FirebaseAuth, it is shorthand syntax to declare class properties initialized from constructor arguments.
It is the same as:

private auth:FirebaseAuth;
constructor(auth: FirebaseAuth) {this.auth = auth;}