Before getting into code, I have a conceptual question: I'm routing from component A (Main list of items) to component B (form to create new item), and then from component B back to component A. I would like to update the component A with the new item. One option is by subscribing to a subject in a service which injected to these 2 components. I would like to know if there is a another option. I'm aware the routing saves state of the component and the ngOnInit event is not invoked when routing back to component A, so I can't use this event for subscribing to the service. Is there another life cycle event I can use when re-routing to the component ?
0
votes
2 Answers
0
votes
0
votes
I would use a RouteGuard to pre-load the data for the component with a canActivate function. It will block the route to continue until the data needed has been loaded, then allow it to continue and render the view.
In your routing configuration you would do something like
export const ROUTES: Routes = [
//...
{
path: 'example',
component: ExampleComponent,
canActivate: [PreloadDataGuard] //<--
}
//...
];
The guard will handle loading of the data and should return an Observable<boolean> or a Promise<boolean> when done.
This is even easier if you use a store pattern for your data, such as NGRX or NGXS or Redux. In that case, have a look at this article, even though I think it can help you further along even if you're not using a store.