declare properties in constructor angular 2

后端 未结 1 1721
野趣味
野趣味 2021-02-09 20:35

I am a java programer that just has landed in angular 2. When doing the official tutorial, I was surprised to see that they declare this properties in the constructor instead of

相关标签:
1条回答
  • 2021-02-09 21:32

    While this:

    private router: Router
    private heroService: HeroService
    

    just declares two private properties of your class of type Router and HeroService,

    this:

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

    injects an instance of Router (and HeroService), additionally creates two private properties and assigns the injected instances of your services to these in one statement.

    For a better understanding, this does the same:

    private _router: Router;
    private _heroService: HeroService;
    
    constructor(router: Router, heroService: HeroService) {
        this._router = router;
        this._heroService = heroService;
    }
    

    With the "first approach" you don't have an instance of these services.

    Sidenote: providers: [Router, HeroService] which you might have somewhere in one of your Component Anntations just give your components the possibility to inject them, but doesn't actually do it, that's why you probably end up injecting them always via your constructor method.

    0 讨论(0)
提交回复
热议问题