I am working on an Angular project. I'm struggling with refresh action in a component.
I would like to refresh the router's components on button click.
I have refresh button when I click on it the component/router need to be refresh.
I tried window.location.reload()
and location.reload()
these two are not suitable for my need. Please help if anyone aware of it.
This question is related to
angular
routes
components
refresh
this is little bit out of box and I dont know whether this helps you or not but have yo tried
this.ngOnInit();
its a function so whatever code you have in it will be recalled just like a refresh.
constructor(private router:Router, private route:ActivatedRoute ) {
}
onReload(){
this.router.navigate(['/servers'],{relativeTo:this.route})
}
Fortunately, if you are using Angular 5.1+, you do not need to implement a hack anymore as native support has been added. You just need to set onSameUrlNavigation to 'reload' in the RouterModule options :
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
More information can be found here: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
Other way to refresh (hard way) a page in angular 2 like this
it's look like f5
import { Location } from '@angular/common';
constructor(private location: Location) {}
pageRefresh() {
location.reload();
}
just do this : (for angular 9)
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
constructor(@Inject(DOCUMENT) private document: Document){ }
someMethode(){ this.document.location.reload(); }
Adding this to code to the required component's constructor worked for me.
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;
}
});
Make sure to unsubscribe
from this mySubscription in ngOnDestroy()
.
ngOnDestroy() {
if (this.mySubscription) {
this.mySubscription.unsubscribe();
}
}
Refer to this thread for more details - https://github.com/angular/angular/issues/13831
router.navigate['/path']
will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page
One more way without explicit route:
async reload(url: string): Promise<boolean> {
await this.router.navigateByUrl('.', { skipLocationChange: true });
return this.router.navigateByUrl(url);
}
In my application i have component and all data is coming from API which i am calling in Component's constructor. There is button by which i am updating my page data. on button click i have save data in back end and refresh data. So to reload/refresh the component - as per my requirement - is only to refresh the data. if this is also your requirement then use the same code written in constructor of component.
Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!
DeleteEmployee(id:number)
{
this.employeeService.deleteEmployee(id)
.subscribe(
(data) =>{
console.log(data);
this.ngOnInit();
}),
err => {
console.log("Error");
}
}
kdo
// reload page hack methode
push(uri: string) {
this.location.replaceState(uri) // force replace and no show change
await this.router.navigate([uri, { "refresh": (new Date).getTime() }]);
this.location.replaceState(uri) // replace
}
Just change the routeReuseStrategy from the angular Router:
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
Set the routerproperty "navigated" to false:
this._router.navigated = false;
Then navigate to your component:
this._router.navigate(['routeToYourComponent'])
After that reinstate the old/default routeReuseStrategy:
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
You can also make a service out of this:
@Injectable({
providedIn: 'root'
})
export class RouterService {
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
reuseRoutes(reuse: boolean) {
if (!reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
if (reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
async refreshPage(url?: string) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this._router.navigated = false;
url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
This can be achieved via a hack, Navigate to some sample component and then navigate to the component that you want to reload.
this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);
html file
<a (click)= "getcoursedetails(obj.Id)" routerLinkActive="active" class="btn btn-danger">Read more...</a>
ts file
getcoursedetails(id)
{
this._route.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this._route.navigate(["course",id]);
});
Source: Stackoverflow.com