Search code examples
javascriptangulartypescriptangular-router

Why make router private?


In the Angular 2+ (4) routing tutorial, it shows to make the router a private member, e.g:

constructor(
    private router: Router, // <- router is private
    private heroService: HeroService) { }
    ...
) {}

But it doesn't provide any explanation as to why router is private here. Having it private makes it harder to test, so what is the reason for it being private? Is it just best-practice, or is there some security implication of having it public?

Also, specifically, how to test routing, that the right routes are navigated to in different circumstances? The tutorial does not mention testing router/routes at all?


Solution

  • Adding private, public, or protected implicitly adds a class-level field where the passed constructor parameter is assigned to.

    This is a TypeScript feature for less boilerplate.

    You can now access the passed value using

    someMethod() {
      this.router...
    }
    

    instead of

    class MyComponent {
      router:Router;
    
      constructor(
        router: Router, // <- router is private
        private heroService: HeroService) { }
        ...
      ) {
        this.router = router;
      }
    
      someMethod() {
        this.router...
      }
    }
    

    If there is no specific reason to make it public or protected, private is the right option. This is what they did.