Reputation: 311
I'm having an issue with Routing in Angular2 where routing creates a new object and keeps the old object.
My navbar and [Home] button resides in the AppComponent.
.. app.html
<a class="navbar-brand" [routerLink]="['Auth']">Home</a>
<router-outlet></router-outlet>
..
The router defaults to AuthComponent at the start.
.. app.component.ts
@RouteConfig([
{ path: '/', as: 'Auth', component: AuthComponent, useAsDefault: true }
])
..
I'll demonstrate the scenario by logging a message in AuthComponent's constructor.
.. auth.component.ts
constructor(private _router: Router) {
console.log("Constructing AuthComponent");
this.router = _router;
}
..
The response to clicking the Home button will produce Constructing AuthComponent
everytime it is clicked thus creating a new object. (I can confirm that the old objects do still exist)
I want to be able to route to somewhere and then route back into AuthComponent while still having access to my data I set previously.
See this plunker.
I'm currently using Updated to 2.0.0-beta.7
2.0.0.beta.9
Upvotes: 0
Views: 398
Reputation: 202156
You could use the CanReuse
interface on your component and its routerCanReuse
method. This way, if this method returns true
, the same instance of the component will be used within routing:
@Component({
(...)
})
class SomeComponent implements CanReuse {
constructor(params: RouteParams) {
}
routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) {
return true;
}
}
See this link for more details:
Upvotes: 1