1
votes

Not sure if this is a bug or not. When using a RouteProvider, the code within a controller constructor runs every time the route changes. So, in the following example, I call fetchData() to load the initial data that is loaded in a view.

@NgController(
    selector: '[my-controller]',
    publishAs: 'ctrl'
)
class MyController implements NgDetachAware {
  ...

  MyController(RouteProvider router) {
    linkId = router.parameters['linkId'];
    route = router.route.newHandle();
    fetchData();
  }
}

But anytime I navigate to a route, the code in the constructor executes, and the data gets fetched.

Is this a bug? If not, what is the correct way to set values when the view loads?

1
Yup, this is expected. Your controllers get destructed and constructed every time the route (and implicitly the associated controller) changes. Store your data in a service. Those are persistent. - Sergiu Paraschiv
Excellent. Makes sense. - Shailen Tuli

1 Answers

2
votes

If your controller is used inside the view then that view is destroyed and re-created every time route is re-entered or parameters change, so new instance of the controller is created.