Mohammad Fareed
Mohammad Fareed

Reputation: 1972

Angular refresh component

i have location drop down in top nav bar. on change location, i have to load entire application based on that location data, so i need to get all components data to be refreshed, that is why i am approaching this step.

core.js:5847 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'RefreshComponent' Error: Cannot match any routes. URL Segment: 'RefreshComponent'

constructor(
private router: Router,
) { }

i have used javascript setTimeout(() => { location.reload(); }); it worked fine, i dont want to reload the page, just want to refresh the component i tried below code. but when i use console error is coming.

changeLocation(locationData) {
    this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
        this.router.navigate([this.router.url]);
    }); 
}

Am i missing any configuration .?

Upvotes: 3

Views: 29802

Answers (2)

Plochie
Plochie

Reputation: 4117

You probally dont have RefreshComponent route in you route configuration.

As far as refresing your component goes, just modify your function as follows, you don't need RefreshComponent route.

Replace navigateByUrl('/RefreshComponent',... with navigateByUrl('/',...

changeLocation(locationData) {

    // save current route first
    const currentRoute = this.router.url;

    this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
        this.router.navigate([currentRoute]); // navigate to same route
    }); 
}

Upvotes: 11

Jalpesh Vadgama
Jalpesh Vadgama

Reputation: 14216

Here is the link you are looking for.

https://medium.com/@rakshitshah/refresh-angular-component-without-navigation-148a87c2de3f

As per the link.

mySubscription: any;

Add following in the constructor of your component.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
};

this.mySubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
  // Trick the Router into believing it's last link wasn't previously loaded
  this.router.navigated = false;
  }
});

And make sure to unsubscribe to "mySubscription" like below

ngOnDestroy() {
 if (this.mySubscription) {
   this.mySubscription.unsubscribe();
 }
}

Upvotes: 0

Related Questions