Search code examples
angulartypescriptdependency-injectionscopeangular-services

Why does angular's dependency injection need private or public to work?


I have noticed that an angular class doesn't recognize an injected service if it hasn't been injected with explicit scope definition.

This following code doesn't work

constructor(router: Router) {}

but this one does.

constructor(private router: Router) {}

Can anyone explain why? I believe that if you don't explicitly write the property's scope definition, then it is public by default, like classes properties, but seems like is not the case in here.


Solution

  • Whatever you define in your constructor is taken as a parameter. It is a TypeScript convenience that you can attach an accessor to it. For instance:

    constructor(private router: Router) {}
    

    is a shorthand for ES6:

    constructor(router) {
      this.router = router;
    }
    

    Dependency injection still works though, if you do the following:

    constructor(router: Router) {
      // router only available in this scope
    }
    

    It's just that it's only available inside the constructor, and not in the class instance, because it's inside the constructor {} scope. A class field is defined in the class {} scope, and therefore accessible in the entire class