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