Angular 5:如何仅使用1条路径将出口的所有路径路由到同一个组件?

tho*_*rn̈ 8 angular angular-router angular-auxiliary-routes

我目前的配置:

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

有用.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)
Run Code Online (Sandbox Code Playgroud)

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

  • (1) 是用来 (c)
  • (2)用于(a)(b)

这就是为什么NavComponent实例被破坏并重新创建每个位置的变化,从说时间(c)(a).这是我需要防止的事情.我需要保留我的实例,因为它的状态,动画等等.据我所知,只有在所有URL使用相同的路由时才有可能,但是我找不到这样做的方法.如果我删除(1),喜欢的URL (c)停止显示NavComponentnav.显然**不符合这样的URL(我不知道为什么).

你可以在这里看到它:https://stackblitz.com/edit/angular-ptzwrm

这里有什么合适的解决方案?

就目前而言,我最重要的UrlSerializer(nav:)(c)在解析之前添加到URL ,但感觉就像是黑客.

Dav*_*vid 3

愚蠢的问题,但是您不能简单地使用位置服务修改 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 { }
Run Code Online (Sandbox Code Playgroud)

这是修改后的 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

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