Angularユニバーサルアプリケーションに取り組んでいます。カスタムプレフィックスを使用して動的ルートを作成したいのですが、私のケースに関連する役立つドキュメントが見つかりません。ヘルプをいただければ幸いです...
詳細:
私が持っているのは、次の4つの異なる動的URLを持つ4つのページがあります。
http://example.com/
)http://example.com/{category_name}
)http://example.com/{category_name}/{sub_category_name}
)http://example.com/p{product_id}-{product_name}
)http://example.com/user{user_id}-{user_name}
)私がしたこと
ホーム、カテゴリ、サブカテゴリのページを処理する単一のルートを登録しました。これらは、以下で説明する動的なカテゴリレベルと同じUIを持っているためです。
RouterModule.forRoot([
{path: '**', component: HomeComponent, data: {title: 'Home', description: 'Homepage - quick overview.'}}
])
苦労:
現在、製品とユーザーページのルートを追加できません。スラッシュの後、製品のp
の前にuser
とids
のプレフィックスを追加する方法を理解できません。それぞれとユーザーページ。これらのプレフィックスがないと、ルーティングは正常に機能します。
製品およびユーザーページに必要なURLの例
私は使っている @angular/router
ルーティング用。
前もって感謝します。
@Yuriyがこれを再開してくれてありがとう、@IngoBürkのコメントからすでに答えを得ています。下記のGistは、正規表現を通るルートを作成するのに役立ちました。 https://Gist.github.com/matanshukry/22fae5dba9c307baf0f364a9c9f7c115
参考までに、以下のソースを追加しました。
/**
* Copyright (c) Matan Shukry
* All rights reserved.
*/
import { UrlSegment, UrlSegmentGroup, Route } from '@angular/router';
// export type UrlMatchResult = {
// consumed: UrlSegment[]; posParams?: { [name: string]: UrlSegment };
// };
export function ComplexUrlMatcher(paramName: string, regex: RegExp) {
return (
segments: UrlSegment[],
segmentGroup: UrlSegmentGroup,
route: Route) => {
const parts = [regex];
const posParams: { [key: string]: UrlSegment } = {};
const consumed: UrlSegment[] = [];
let currentIndex = 0;
for (let i = 0; i < parts.length; ++i) {
if (currentIndex >= segments.length) {
return null;
}
const current = segments[currentIndex];
const part = parts[i];
if (!part.test(current.path)) {
return null;
}
posParams[paramName] = current;
consumed.Push(current);
currentIndex++;
}
if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || currentIndex < segments.length)) {
return null;
}
return { consumed, posParams };
}
}
使い方、
/**
* Copyright (c) Matan Shukry
* All rights reserved.
*/
export const UserRoutes: Routes = [
{
path: 'users',
component: UserComponent,
children: [
{
path: '',
component: UserListComponent
},
{
matcher: ComplexUrlMatcher("id", /[0-9]+/),
component: UserItemComponent
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(UserRoutes)],
exports: [RouterModule]
})
export class UserRoutingModule { }
http://example.com/p{product_id}-{product_name}
を作成するには、product_idセグメントを:product_id
として、product_nameセグメントを:product_name
として分割します。次に、app.routing.jsルーティングファイルに移動し、URLを次のように設定する必要があります。
{ path: 'http://example.com/p/:product_id/-/:product_name', component: ProductComponent }
通常、router
は、特定の入力文字列(url
)を特定のパターン(route
)に一致させる必要があります。 single入力がmultipleパターンと一致しないことを確認する必要があります。一致しない場合、ルーターはどちらの方向に進むかわかりません。
そうは言っても、Angularには[RouteGuard][1]
の概念があります。 RouteGuard(またはその派生物)は、URLが特定のルートに一致すると、ルーティングプロセスにフックを与えます。