简体   繁体   中英

Syntax for Dependency Injection in Angular2

In Angular Components, written in typescript, it is possible to declare a class member (variable) as parameter of the constructor. My question is about why to do so.
To make myself clear, see the snippets below. Both have identical meaning.

  • The first is the classic way to define a private member using dependency injection mechanism (as it is done in most OO languages).
  • The latter is, if I'm not mistaken, a specificity of TypeScript.

export class HeroListComponent implements OnInit {
    // private member declaration
    private heroService:HeroService;

    // constructor signature
    constructor(service:HeroService) {
        // private member assignment
        this.heroService = service;
    }
}

export class HeroListComponent implements OnInit {
    // here the private member is declared inside the constructor signature
    constructor(private heroService:HeroService) { }
}

In my opinion, the first syntax is clearer and easier to understand for people unfamiliar with TypeScript.
So, I was wondering if there is any particular reason, apart from being shorter (which does not really matters since the code will eventually be minified/uglyfied), to use the latter. Thanks.

Edit: This answer addresses the original question (now edited), where the second example looked like this:

export class HeroListComponent implements OnInit {
    // here the private member is declared inside the constructor signature
    constructor(private service:HeroService) { 
        this.heroService = service;
    }
}

In the second example, you are actually creating two class properties. Both this.service and this.heroService will exist in your object.

Your second example is like doing this:

export class HeroListComponent implements OnInit {
    private heroService: HeroService;
    private service: HeroService;

    constructor(service:HeroService) {
        this.service = service;
        this.heroService = service;
    }
}

The style in the second example would benefit you if your class property can have the same name as the parameter in the constructor. If they could both be named heroService , then you could just do:

export class HeroListComponent implements OnInit {
    constructor(private heroService:HeroService) {  }
}

The benefit is just that it removes clutter. Both the declaration of the property in the class and the assignment of the constructor parameter to that class property are gone. It may not necessarily be cleaner or more readable to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM