我试图建立UrlMatcher工厂
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'); }
但编译器抱怨:
输入' {matcher :()=> UrlMatcher; component:typeof DummyComponent; } ...'不能分配到'路由[]'。
用例:
我需要匹配网页(在NavigationNode[]
中描述)并在特定的模板组件中进行渲染。页面可以有多个URL(用于迁移目的,本地化URL等)。
这是匹配逻辑:
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));
这可以很容易地扩展为使用不同的匹配,例如Regex:
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));
答案 0 :(得分:0)
matcher
属性应实现UrlMatcher
类型:
export declare type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult;
所以我建议你改变代码:
export function dummyMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route): UrlMatchResult {
const factory = matchUrlFn(sitemap as any, 'dummy');
return factory(segments, group, route);
}
答案 1 :(得分:0)
面向新手,他们面对AOT编译器的问题
您需要将粗箭头功能移动到普通的ES5功能并export
(即使您没有在其他任何地方使用它)
移动此
const routes: Routes = [
{
component: SomeComponent,
matcher: () => { //your url matcher },
}
,...
];
到
export function yourUrlMatcher( //params ) { //your function here }
const routes: Routes = [
{
component: SomeComponent,
matcher: yourUrlMatcher,
}
,...
];