角度2:在同一路线上重定向时再次重新加载相同的组件

Er *_*rma 6 angular2-forms angular2-directives angular2-template angular

我使用'routerLink'来导航我的路线,它工作正常.但是,当我再次点击同一个按钮时,我希望该组件将再次加载.但目前,它不适用于angular2.

app.component.html

<ul class="nav navbar-nav navbar-right">
            <li><a [routerLink]="['/events']" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">All Events</a></li>
            <li><a [routerLink]="['/events/new']" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">Create New</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我想,当我一次又一次点击"所有事件"选项卡时,每次都会加载事件组件.

如何在angular2中实现这种情况?

Par*_*ain 5

我想,当我一次又一次点击"所有事件"选项卡时,每次都会加载事件组件.

这是Not Possible在angular2,原因是一旦你加载任何组件,只有当你从另一条路线再次导航到该路线时,该组件才会重新加载.

但你可以强行重装

基本上有两种方法

  • 您可以ngOnInit()根据需要一次又一次地调用方法,这不是推荐的方法

  • 你可以调用一个commonn方法,ngOnInit()然后根据需要再次调用该函数

    ngOnInit(){
        this.callingFunction();
    }
    
    forLaterUse(){
        this.callingFunction(); 
    }
    
    Run Code Online (Sandbox Code Playgroud)

另一种方法是如果你想在param change上加载相同的组件,你可以在构造函数中使用它

this.route.params.subscribe((params: Params) => {
    console.log(params); 
    this.callingFunction();
    // this will be called every time route changes
    // so you can perform your functionality here

});
Run Code Online (Sandbox Code Playgroud)


Ano*_*ous 5

下面的这个github链接有正确的解决方案 https://github.com/angular/angular/issues/13831

将以下代码放入要加载的组件的构造函数中

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

this.router.events.subscribe((evt) => {
  if (evt instanceof NavigationEnd) {
    this.router.navigated = false;
    window.scrollTo(0, 0);
  }
});
Run Code Online (Sandbox Code Playgroud)