0
我試圖做一個UrlMatcher工廠AOT和功能工廠(動態路由模板)
export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy');
export const routes: Routes = [
{ matcher: dummyMatcher, component: DummyComponent },
{ path: '**', component: DummyComponent },
];
但是,這並不與AOT工作... 我們如何處理功能工廠,AOT?
我試圖
export function dummyMatcher(): UrlMatcher { return routeMatcher(sitemap as any, 'dummy'); }
但是編譯器抱怨:
類型「{匹配:()=> UrlMatcher; component:typeof DummyComponent; } ...'不能分配給'Route []'類型。
使用案例:
我需要匹配的網頁(在NavigationNode[]
描述),並使其在特定的模板組件。頁面可以有多個網址(用於遷移目的,本地化的網址等)。 這裏的匹配邏輯:
import { UrlSegment, UrlSegmentGroup, Route, UrlMatchResult } from '@angular/router';
import { inArray } from '@core/utils';
export interface NavigationNode {
...
title?: string;
template?: string;
urls?: string[];
}
/**
* https://angular.io/api/router/UrlMatcher
*/
export const UrlMatcherFactory = (conditions) =>
(segments: UrlSegment[], group: UrlSegmentGroup, route: Route): UrlMatchResult =>
conditions(segments) ? ({ consumed: segments }) : null;
export const matchUrl = (nodes: NavigationNode[], template?: string) =>
(segments: UrlSegment[]) => nodes
.filter(node => template ? node.template === template : true)
.some(node => inArray(node.urls)(`/${segments.join('/')}`));
export const matchUrlFn= (nodes: NavigationNode[], template?: string) =>
UrlMatcherFactory(matchUrl(nodes, template));
這可以容易地擴展到使用不同的匹配,例如正則表達式:
export const matchRegex = (nodes: NavigationNode[]) =>
(segments: UrlSegment[]) => nodes
.some(node => /\w+\/xyz/\d{1, 3}/.test(node.title)); /* bad example (: */
export const matchRegexFn = (nodes: NavigationNode[], template?: string) =>
UrlMatcherFactory(matchRegex(nodes));
是的,這個工程,它導致我最終版本'導出函數dummyMatcher():UrlMatcher {返回routeMatcher(sitemap任何'虛擬')。 }'...我試圖讓它保持輕量級,因爲有匹配器的幾條路線,所以在另一個地方隔離邏輯使得它更容易處理。謝謝。 – Sasxa
不客氣!是的,你的代碼會更短:) – yurzui