RouteConfig and classes, why is the constructor required to need a service and router?

Issue

I have been working with some sample code in the Angular2 framework. The Heroes sample, for example. There is 1 thing I am currently not understanding. What is the factor that says my constructor needs to be Router, Service or viceversa.

I currently understand why they are needed for @RouteConfig to work, and the Service for the calls, but what is the explicit factor in saying “Because of X, you need the constructor to be Router, Service”

Is it that the class implemented OnInit? Is it that the class is referenced in the application component’s RouteConfig? What makes the order as such, could I just reverse it the other way around?

That last question, I determined was a no-go, if i had 1 compoennt defined as Router,Service while another was Service, Router

If someone can give me some insight as to why this needs to be set up this way and where the definitions come from, it would better help me understand the concepts of Angular 2 more.

If you can point me to important doc files for this, that would be amazing too so i can read more.

Solution

If you have a constructor like

constructor(private router:Router, private service:Service) {}

then you tell Angulars DI that a Router instance should be passed as first constructor parameter and a Service instance as the 2nd contructor parameter when Angular needs to create an instance of that class.

Angulars DI then looks up the providers in its injector tree and returns an instance from the injector that finds a matching provider.

For that to work the class needs to have a decorator like @Component(), @Directive(), @Pipe(), or @Inectable() and it only works for instances created by Angular. If you use new Service() or new Router() you are on your own and need to acquire and pass the required constructor parameters explicitely.

Answered By – Günter Zöchbauer

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.