[英]In Angular 4, how do I target an auxiliary outlet with a child route?
[英]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:
(1)
用於(c)
(2)
用於(a)
和(b)
這就是為什么每次位置更改從(c)
到(a)
都會銷毀並重新創建NavComponent
實例的原因。 這是我需要防止的事情。 由於實例的狀態,動畫等原因,我需要保留實例。據我了解,只有對所有URL使用相同的路由才有可能,但是我找不到實現此目的的方法。 如果刪除(1)
,則類似(c)
的URL NavComponent
在nav
停止顯示NavComponent
。 顯然**
與此類網址不匹配(不過我不確定為什么)。
您可以在這里查看它的運行情況: https : //stackblitz.com/edit/angular-ptzwrm
這里合適的解決方案是什么?
目前,我正在覆蓋UrlSerializer
以便在解析之前將(nav:)
添加到(c)
類的URL中,但這感覺像是一種hack。
愚蠢的問題,但是您是否不能簡單地使用定位服務修改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
角路由器策略的默認值: https : //github.com/angular/angular/blob/master/packages/router/src/route_reuse_strategy.ts
我的意思是,您需要的是嵌套的路由器插座。 像這樣:
app.component.html: <router-outlet></router-outlet>
feature-area.component.html: <your-navbar-component></your-navbarcomponent> <router-outlet></router-outlet>
child-of-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
您將獲得:
這里的一些鏈接...
嗨,您好!
如果需要,我可以寫一些示例,以更好地解釋。 但是我的意思是,您使路由器超載了一項可能對他而言不重要的任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.