首页 文章

如何使用angular 2路由器重新加载当前路由

提问于
浏览
72

我正在使用带有哈希定位策略的角度2 .

该组件加载了该路由:

"departments/:id/employees"

到目前为止很好 .

在我成功批量保存多个已编辑的表行后,我想通过以下方式重新加载当前路由URL:

this.router.navigate([`departments/${this.id}/employees`]);

但没有任何反应,为什么?

22 回答

  • -4

    对我来说,用硬编码工作

    this.router.routeReuseStrategy.shouldReuseRoute = function() {
        return false;
        // or
        return true;
    };
    
  • 52

    如果您的navigate()不会更改已在浏览器地址栏上显示的URL,则路由器无需执行任何操作 . 刷新数据不是路由器的工作 . 如果要刷新数据,请创建注入组件的服务并调用服务上的加载功能 . 如果将检索新数据,它将通过绑定更新视图 .

  • 1

    我在Angular的GitHub功能请求中找到了此解决方法:

    this._router.routeReuseStrategy.shouldReuseRoute = function(){
        return false;
    };
    
    this._router.events.subscribe((evt) => {
        if (evt instanceof NavigationEnd) {
            this._router.navigated = false;
            window.scrollTo(0, 0);
        }
    });
    

    我尝试将其添加到我的 app.component.ts ngOnInit 函数中,它确实有效 . 现在,对同一链接的所有进一步点击都会重新加载 component 和数据 .

    Link to original GitHub feature request

    积分在GitHub上转到 mihaicux2 .

    我在版本 4.0.0-rc.3 上用 import { Router, NavigationEnd } from '@angular/router'; 测试了这个

  • 2

    现在可以使用Router config的 onSameUrlNavigation 属性在Angular 5.1中完成此操作 .

    我添加了一个博客,解释了这里的内容,但其主旨如下

    https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

    在路由器配置中启用 onSameUrlNavigation 选项,将其设置为 'reload' . 当您尝试导航到已经处于活动状态的路由时,这会导致路由器触发事件周期 .

    @ngModule({
     imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
     exports: [RouterModule],
     })
    

    在路径定义中,将 runGuardsAndResolvers 设置为 always . 这将告诉路由器始终启动警卫和解析器循环,触发相关事件 .

    export const routes: Routes = [
     {
       path: 'invites',
       component: InviteComponent,
       children: [
         {
           path: '',
           loadChildren: './pages/invites/invites.module#InvitesModule',
         },
       ],
       canActivate: [AuthenticationGuard],
       runGuardsAndResolvers: 'always',
     }
    ]
    

    最后,在要启用重新加载的每个组件中,您需要处理事件 . 这可以通过导入路由器,绑定到事件并调用重置方法来完成,该方法重置组件的状态并在需要时重新获取数据 .

    export class InviteComponent implements OnInit, OnDestroy {
     navigationSubscription;     
    
     constructor(
       // … your declarations here
       private router: Router,
     ) {
       // subscribe to the router events. Store the subscription so we can
       // unsubscribe later.
       this.navigationSubscription = this.router.events.subscribe((e: any) => {
         // If it is a NavigationEnd event re-initalise the component
         if (e instanceof NavigationEnd) {
           this.initialiseInvites();
         }
       });
     }
    
     initialiseInvites() {
       // Set default values and re-fetch any data you need.
     }
    
     ngOnDestroy() {
       if (this.navigationSubscription) {
         this.navigationSubscription.unsubscribe();
       }
     }
    }
    

    完成所有这些步骤后,您应该启用路由重新加载 .

  • 34

    在控制器中创建一个函数,重定向到预期的路由,如此

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

    然后像这样使用它

    this.redirectTo('//place your uri here');
    

    此功能将重定向到虚拟路由并快速返回到目标路由,而无需用户意识到 .

  • 28

    有点棘手:使用相同的路径与一些虚拟参数 . 例如-

    refresh(){
      this.router.navigate(["/same/route/path?refresh=1"]);
    }
    
  • -2

    Angular 2-4 route reload hack

    对我来说,在根组件(组件,存在于任何路由上)中使用此方法可以:

    onRefresh() {
      this.router.routeReuseStrategy.shouldReuseRoute = function(){return false;};
    
      let currentUrl = this.router.url + '?';
    
      this.router.navigateByUrl(currentUrl)
        .then(() => {
          this.router.navigated = false;
          this.router.navigate([this.router.url]);
        });
      }
    
  • 0

    找到了一个快速而直接的解决方案,不需要修补角度的内部工作:

    基本上:只需创建一个具有相同目标模块的备用路由,然后在它们之间切换:

    const routes: Routes = [
      {
        path: 'gesuch',
        loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
      },
      {
        path: 'gesuch-neu',
        loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
      }
    ];
    

    这里的toggeling菜单:

    <ul class="navigation">
        <li routerLink="/gesuch-neu" *ngIf="'gesuch' === getSection()">Gesuch</li>
        <li routerLink="/gesuch" *ngIf="'gesuch' !== getSection()">Gesuch</li>
    </ul>
    

    希望能帮助到你 :)

  • 3

    在param更改重新加载页面将不会发生 . 这是非常好的功能 . 无需重新加载页面,但我们应该更改组件的值 . paramChange方法将调用url更改 . 所以我们可以更新组件数据

    /product/: id / details
    
    import { ActivatedRoute, Params, Router } from ‘@angular/router’;
    
    export class ProductDetailsComponent implements OnInit {
    
    constructor(private route: ActivatedRoute, private router: Router) {
        this.route.params.subscribe(params => {
            this.paramsChange(params.id);
        });
    }
    
    // Call this method on page change
    
    ngOnInit() {
    
    }
    
    // Call this method on change of the param
    paramsChange(id) {
    
    }
    
  • 0

    就我而言:

    const navigationExtras: NavigationExtras = {
        queryParams: { 'param': val }
    };
    
    this.router.navigate([], navigationExtras);
    

    工作正确

  • 66

    实现OnInit并在route.navigate()的方法中调用ngOnInit()

    看一个例子:

    export class Component implements OnInit {
    
      constructor() {   }
    
      refresh() {
        this.router.navigate(['same-route-here']);
        this.ngOnInit();   }
    
      ngOnInit () {
    
      }
    
  • 2

    通过使用 reload 的虚拟组件和路由解决了类似的情况,实际上是 redirect . 这绝对不包括所有用户场景,但仅适用于我的场景 .

    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';
    import { Http } from '@angular/http';
    
    @Component({
      selector: 'reload',
      template: `
        <h1>Reloading...</h1>
      `,
    })
    export class ReloadComponent implements OnInit{
      constructor(private router: Router, private route: ActivatedRoute) {
      }
    
      ngOnInit() {
        const url = this.route.snapshot.pathFromRoot.pop().url.map(u => u.path).join('/');
        this.router.navigateByUrl(url);
      }
    }
    

    路由已连线以使用通配符捕获所有URL:

    import { RouterModule } from '@angular/router';
    import { NgModule } from '@angular/core';
    import { LoginViewComponent } from './views/login/login.component';
    import { HomeViewComponent } from './views/home/home.component';
    import { ReloadComponent } from './views/reload/reload.component';
    
    @NgModule({
      declarations: [ 
        LoginViewComponent, HomeViewComponent, ReloadComponent
      ],
      imports: [
        RouterModule.forRoot([
          { path: 'login', component: LoginViewComponent },
          { path: 'home', component: HomeViewComponent },
          { 
            path: 'reload',
            children: [{
              path: '**',
              component: ReloadComponent 
            }]
          },
          { path: '**', redirectTo: 'login'}
        ])
      ],
      exports: [
        RouterModule,
      ],
      providers: [],
    
    })
    export class AppRoutingModule {}
    

    要使用它,我们只需要将reload添加到我们想要去的url:

    this.router.navigateByUrl('reload/some/route/again/fresh', {skipLocationChange: true})
    
  • 1

    有点硬核但是

    this.router.onSameUrlNavigation = 'reload';
    this.router.navigateByUrl(this.router.url).then(() => {
    
        this.router.onSameUrlNavigation = 'ignore';
    
    });
    
  • 2

    这对我来说就像一个魅力

    this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
    this.router.navigate([<route>]));
    
  • -18

    刷新当前路线有不同的方法

    Change router behaviour (Since Angular 5.1) 将路由器onSameUrlNavigation设置为'reload' . 这将在相同的URL导航上发出路由器事件 .

    • 然后您可以通过订阅路线来处理它们

    • 您可以将它与runGuardsAndResolvers的组合一起使用以重新运行解析器

    Leave the router untouched

    • 使用URL中的当前时间戳传递刷新queryParam,并在路由组件中订阅queryParams .

    • 使用router-outlet的activate事件来保持路由组件 .

    我在https://medium.com/@kevinkreuzer/refresh-current-route-in-angular-512a19d58f6e下写了更详细的解释

    希望这可以帮助 .

  • 0

    订阅路由参数更改

    // parent param listener ie: "/:id"
        this.route.params.subscribe(params => {
            // do something on parent param change
            let parent_id = params['id']; // set slug
        });
    
        // child param listener ie: "/:id/:id"
        this.route.firstChild.params.subscribe(params => {
            // do something on child param change
            let child_id = params['id'];
        });
    
  • 3

    假设要刷新的组件的路由是 view ,然后使用:

    this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
      if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
        return false;
      }
      return (future.routeConfig === curr.routeConfig);
    };
    

    您可以在方法中添加 debugger ,以了解导航到 "departments/:id/employees" 后的确切路线是什么 .

  • 5

    一种解决方案是传递一个虚拟参数(即以秒为单位的时间),这样就可以重新加载链接:

    this.router.navigate(["/url", {myRealData: RealData, dummyData: (new Date).getTime()}])
    
  • 2

    这对我有用:

    let url = `departments/${this.id}/employees`;
    
    this.router.navigated = false;
    this.router.navigateByUrl(url);
    
  • 12

    reload current route in angular 2非常有用的链接,可以在angualr 2或4中重新加载当前路由

    在此定义了两种技术来做到这一点

    • 与虚拟查询参数

    • 带虚拟路线

    更多见上面的链接

  • 29

    试试这个

    window.open('dashboard','_ self');

    它的旧方法但适用于所有角度版本,它在路由上重定向并刷新页面 .

  • -2

    只需使用原生的javascript重载方法:

    reloadPage() {
        window.location.reload();
    }
    

相关问题