2017-08-13 18 views
0

私はUrlMatcher工場IBMアカデミーと機能工場(動的経路テンプレート)

export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy'); 

export const routes: Routes = [ 
    { matcher: dummyMatcher, component: DummyComponent }, 
    { path: '**', component: DummyComponent }, 
]; 

を作成しようとしている。しかし、これはIBMアカデミーでは動作しません... はどのように我々は、IBMアカデミーと機能の工場を扱うのですか?

Iは

export function dummyMatcher(): UrlMatcher { return routeMatcher(sitemap as any, 'dummy'); } 

を試みたが、コンパイラが不満さ:

タイプ「{マッチャー:()=> UrlMatcherと、コンポーネント:DummyComponentの型。 } ... 'はタイプ' Route [] 'に割り当てられません。


ユースケース:

私は(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)); 

これは簡単に異なるマッチングを使用するように拡張することができ、例えば、正規表現:

export declare type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult; 

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

matcherプロパティはUrlMatcherタイプを実装する必要がありますだから私はあなたのようなコードを変更することをお勧めします:

export function dummyMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route): UrlMatchResult { 
    const factory = matchUrlFn(sitemap as any, 'dummy'); 
    return factory(segments, group, route); 
} 
+0

これはうまくいき、最終的なバージョンのexport function dummyMatcher():UrlMatcher {return routeMatcher(sitemap as any、 'dummy')になります。 } '...私はそれを軽く保つようにしています。マッチャーでいくつかのルートがあるので、別の場所でロジックを分離することで、作業がより簡単になります。ありがとう。 – Sasxa

+0

あなたは大歓迎です!そうです、あなたのコードはもっと短くなります:) – yurzui

関連する問題