代码之家  ›  专栏  ›  技术社区  ›  Ben Crowhurst

如何在页面刷新时重置路由器?

  •  2
  • Ben Crowhurst  · 技术社区  · 10 年前

    如果我发现自己在“/discover”并刷新页面,它将保持在那里,但是我希望应用程序重新开始(/splash)。

    const appRoutes: Routes = [
      { path: '', redirectTo: '/splash', pathMatch: 'full' },   
      { path: 'splash'             , component: SplashComponent        },
      { path: 'discover'           , component: DiscoverComponent      },
      { path: 'broadcast'          , component: BroadcastComponent     },
      { path: 'notifications'      , component: NotificationsComponent },
      { path: 'notifications/:key' , component: NotificationComponent  }
    ];
    
    export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
    

    我已尝试放置一个 router.navigate 在我的父AppComponent中调用 OnInit & OnDestroy 然而,它似乎被忽略了。

    ngOnInit( ) : void {
        this.router.navigate(['splash']); 
    }
    

    我还尝试在 自然灾害 路由器本身的方法。

    1 回复  |  直到 10 年前
        1
  •  5
  •   Ben Crowhurst    10 年前

    您可以通过订阅网络中路由器的第一个导航事件来完成 AppComponent 构造器:

        import 'rxjs/add/operator/filter';
        import { Router, NavigationStart } from '@angular/router';
    
        export class AppComponent {
          private subscription: any;
    
          constructor(private router: Router) {
            this.subscription = this.router.events
              .filter(e => e instanceof NavigationStart && e.id === 1)
              .subscribe(e => {
                this.redirectToSplash();
              });
          }
    
          private redirectToSplash() {
            this.router.navigate(["splash"]);
            this.subscription.unsubscribe();
          }
        }