angular / router

The Angular 1 Component Router
MIT License
665 stars 135 forks source link

Which is the use of routerCanReuse in angular2? #396

Open giorgiofran opened 8 years ago

giorgiofran commented 8 years ago

I'm using angular2 (beta.3) with dart. I'trying to understand which is the logic behind the routerCanReuse method.

What I have understood googling and doing some tests on a simple example, is that routerCanReuse is called when the same route as the active one is invoked.

In my component called by the route invocation, I have a variable (only for test) that is incremented in any method call.

What I could see is that if I set a true return value in routerCanDeactivate(), the variable is resetted, while if I return false in routerCanReuse, the variable is not resetted,even if the canActivate function is called immediately after.

In my tests, canReuse is called even if the route parameters are the same. I'm confused because it seem to me that canReuse and canDeactivate, when I route to the same component, have the same meaning.

Obviously it is not like that and I'm missing something.

Is there anyone that can explain me how these methods work?

ArniDzhan commented 8 years ago

you should ask your router related questions on angular/angular but to answer your question, routerCanReuse is triggered on every call to component. There is another hook routerOnReuse which is called only if you try to load the same component which is already loaded and if routerCanReuse returns true. Hope that helps

giorgiofran commented 8 years ago

So resuming, Deactivate creates a new instance, if you return false to the CanDeactivate method, the same instance is used exactly as it is. This allows to maintain the data if it has not been saved yet. Reuse allows you to reinitialize the existing instance. This should be done in the OnReuse method. Returning false in the routerCanReuse is the default (I guess) and the system moves to the deactivation logic. This make sense. Just the last question, If I return false in the CanReuse method, immediately after the CanActivate one is called and only after this the CanDeactivate. I cannot understand this. In my opinion it should be called the CanDeactivate first, and then, if it returns yes, the CanActivate.

ArniDzhan commented 8 years ago

CanDeactivate = can I leave this page if CanDeactivate returns false that means you can leave the page

CanActivate is like resolve used to be, can I access this component. Return true if to allow access OnActivate is run this on component activation

CanReuse checks if you're able to use the same component instance OnReuse is run instead of OnActivate if component is being reused instead of reactivated.