Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2/4. Reuse strategy. How to inform component it's been reused?

We work with NG2/4 stuff. We have implemented a custom reuse strategy to perfrom the navigation from summary to details screens so we have the summary screen stay in same state (prevent it from recreation) when a user clicks back button.

The thing is that when we edit a record in a child screen and we get back to the main one we have to reload the particular data, not all entire master screen. We have to somehow infrom a component that related data has been changed and it has to update.

But in the strategy class there are no methods having access to the component. The are classes but no their instances so it is unclear how to let a component know about the particular change.

public shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
    // I guess here we have to treat it somehow if it is possible
}
like image 570
Damask Avatar asked Sep 20 '17 09:09

Damask


1 Answers

Had the same problem: there is a dozen of components in our application, that are being reused. Luckily all of them are inherited from one abstract class, so this solution was implemented only in one place.

Workaround is pretty ugly, but it covers the need, is very small and easy.

  1. Inject a router into your component.
  2. Subscribe to router events. If your component captures any router event, this probably means that component was left and it must refresh the data once user gets back. So, if you get a router event, put some flag into component
  3. Now all we need is to know, when user came back. We track it by overriding default hook ngDoCheck.
  4. If ngDoCheck callback is being called and your flag is true, set the flag to false and reload the data
constructor(router: Router) {
  super();

  router.events.subscribe(e => {
    if (!this._reloadData) {
      this._reloadData = true;
    }
  });
}

private ngDoCheck() {
  if (this._reloadData) {
    this._reloadData = false;
    this.resetData();
  }
}
like image 85
Alexander Hrytsenko Avatar answered Oct 20 '22 23:10

Alexander Hrytsenko