Angular 5:如何仅使用一条路线将插座的所有路径路由到同一组件?

Angular 5: how do I route all paths for an outlet to the same component using only 1 route?

我目前的配置:

const routes: Routes = [
  { path: '', component: NavComponent, outlet: 'nav' },  // (1)
  { path: '**', component: NavComponent, outlet: 'nav' } // (2)
];

有效。 NavComponent 总是渲染到出口 nav。特别是,它适用于以下所有类型的 URL:

http://example.com/foo(nav:bar)     // (a) non-empty path in nav   -->  (2)
http://example.com/foo(nav:)        // (b) empty path in nav       -->  (2)
http://example.com/foo              // (c) no nav at all           -->  (1)

请注意,路由器匹配到这些 URL 的不同路由:

这就是为什么每次位置从 (c) 变为 (a) 时都会销毁并重新创建 NavComponent 实例的原因。这是我需要防止的事情。我需要保留我的实例,因为它的状态、动画等。据我所知,只有在所有 URL 都使用相同的路由时才有可能,但是我找不到这样做的方法。如果我删除 (1)(c) 等 URL 将停止在 nav 中显示 NavComponent。显然 ** 与此类 URL 不匹配(我不确定为什么)。

您可以在此处查看实际效果:https://stackblitz.com/edit/angular-ptzwrm

这里的正确解决方案是什么?

现在,我 overriding UrlSerializer 在解析之前将 (nav:) 添加到像 (c) 这样的 URL,但感觉就像是 hack。

我的意思是您需要的是 router-outlet 嵌套。像这样:

app.component.html: <router-outlet></router-outlet>

feature-area.component.html: <your-navbar-component></your-navbarcomponent> <router-outlet></router-outlet>

child-的-feature-area.component.html: < h1>Hi there!</h1>

your-navbar-component.component.html: < p>some links here...</p>

当您访问http://localhost:4200/feature-path/child-feature-path 你会得到:

这里有一些链接...

您好!

如果你需要,我可以写一些带有示例的pluker来更好地解释。但我的意思是你正在用一个可能不属于他的任务使路由器超载。

愚蠢的问题,但是你不能简单地修改 URL 使用位置服务并保持在同一个组件上(并且只改变动画的状态)吗?

否则,您可以实施自定义 RouteReuseStrategy 以强制重用您的组件

import { RouteReuseStrategy } from '@angular/router';

import {ActivatedRouteSnapshot} from '@angular/router';
import { DetachedRouteHandle } from '@angular/router';


/** Use defaults from angular internals, apart from shouldReuseRoute **/


 export class CustomReuseStrategy implements RouteReuseStrategy {
    shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
    store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
    shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null { return null; }


   shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
       let name = future.component && (<any>future.component).name;

    return future.routeConfig === curr.routeConfig || name == "NavComponent";
  }
}


@NgModule({

  providers: [

    {
      provide: RouteReuseStrategy,
      useClass: CustomReuseStrategy
    }]
})
export class AppModule { }

这是您修改后的 stackblitz,它将始终重用您的 NavComponent

https://stackblitz.com/edit/angular-tj5nrm?file=app/app.module.ts

链接

路由重用策略解释: https://medium.com/@gerasimov.pk/how-to-reuse-rendered-component-in-angular-2-3-with-routereusestrategy-64628e1ca3eb

angular 路由器策略的默认值:https://github.com/angular/angular/blob/master/packages/router/src/route_reuse_strategy.ts