Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. If you are working with angular and when you need to refresh component without navigation on another component or instead of using window.location.reload() or location.reload(), you can follow below code in your project:
  2.  
  3. <code>mySubscription: any;<code>
  4.  
  5. Adding following code snippet to the required component’s constructor will work.
  6.  
  7. this.router.routeReuseStrategy.shouldReuseRoute = function () {
  8. return false;
  9. };
  10.  
  11. this.mySubscription = this.router.events.subscribe((event) => {
  12. if (event instanceof NavigationEnd) {
  13. // Trick the Router into believing it's last link wasn't previously loaded
  14. this.router.navigated = false;
  15. }
  16. });
  17.  
  18. Make sure to unsubscribe from this mySubscription in ngOnDestroy().
  19.  
  20. ngOnDestroy() {
  21. if (this.mySubscription) {
  22. this.mySubscription.unsubscribe();
  23. }
  24. }
  25.  
  26. Here we just trick the router into believing that, last link was never visited, and on click of button, it will load that component (Refreshing the component).
  27. This trick will work in angular 2/ 4/ 5/ 6/ 7/ 8 version of Angular.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement