How to reload the component of same URL in Angular 2?

心不动则不痛 提交于 2019-12-10 03:04:55

问题


I am trying to reload the same url in Angular 2 by using router.navigate but it is not working. url : http://localhost:3000/landing Scenario : I am on http://localhost:3000/landing and now I am changing a particular parameter in the page which should reload the page.

Code :

let link = ['Landing'];
this.router.navigate(link);

回答1:


Navigate to some dummy component and then navigate to the component that you want to reload. //the second parameter _skipLocationChange=true to avoid that url in back button

this.router.navigateByUrl('/DummyComponent', true);
this.router.navigate(["Landing"]);



回答2:


this.router.navigateByUrl('/DummyComponent', {skipLocationChange: true}).then(()=>
this.router.navigate(["Landing"]));



回答3:


I managed to implement reloading a component by using PlatformLocation:onPopState and NgZone:run in the constructor. It was a work around, but atleast it worked the way it was required.

constructor(
    private route: ActivatedRoute,
    public router: Router,
    private platformLocation: PlatformLocation,
    private ngZone: NgZone) {

    platformLocation.onPopState(() => {
        if(platformLocation.pathname.startsWith("/currentRoute")) {
            this.ngZone.run(() => {
                console.log("Reloading component");
            });
        }
    });
}

onPopState was used as the reloading was supposed to be triggered on browser back/forward button. Also the check for pathname had to be used as the onPopState method was getting invoked on back/forward in any routes as the component is injected.



来源:https://stackoverflow.com/questions/39396075/how-to-reload-the-component-of-same-url-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!