NgRx ルーター ストアを使用した Angular ルーター URL パラメーター
状態を使用してアプリを構築する場合、コンポーネントの状態を初期化するためのエントリ ポイントが鍵となりますが、場合によっては、ユーザーがブックマークできるように URL 内にアプリケーションの状態を保存する必要がある場合があります。または、ユーザー エクスペリエンスを向上させ、ナビゲーションを容易にすることを目的として、特定のアプリケーションの状態を共有します。
ほとんどの場合、コンポーネント内で Angular Router と ActivatedRoute を組み合わせてこれらのケースを解決し、この責任をコンポーネントに委任するか、他のケースではコンポーネントとエフェクトを組み合わせて解決を試みます。
私はメノルカ島で休暇を続けているので、今朝は Angular Router で状態を処理する方法と、ngrx ルーターがコードの改善とコンポーネントの責任の軽減にどのように役立つかを学び、練習しました。
シナリオ
ユーザーが選択した場所の詳細を変更し、URL を共有し、後で同じ状態に戻ることができる編集ページを作成したいと考えています。たとえば、http://localhost/places/2 の場合、2 は編集中の場所の ID です。ユーザーは、アクションを実行した後にホームページに戻ることもできる必要があります。
?この記事は、NgRx の学習に関する私のシリーズの一部です。フォローしたい方はぜひチェックしてみてください。
https://www.danywalls.com/ Understanding-when-and-why-to-implement-ngrx-in-angular
https://www.danywalls.com/how-to-debug-ngrx-using-redux-devtools
https://www.danywalls.com/how-to-implement-actioncreationgroup-in-ngrx
https://www.danywalls.com/how-to-use-ngrx-selectors-in-angular
https://danywalls.com/when-to-use-concatmap-mergemap-switchmap-and-exhaustmap-operators-in-building-a-crud-with-ngrx
リポジトリ start-with-ngrx のクローンを作成します。このプロジェクトには ngrx とアプリケーションが準備されており、ブランチ crud-ngrx に切り替えます
https://github.com/danywalls/start-with-ngrx.git git checkout crud-ngrx
コーディングの時間です!
編集ページ
まずターミナルを開き、Angular CLI を使用して新しいコンポーネントを生成します。
ng g c pages/place-edit
次に、app.routes.ts を開き、パラメーター /places/:id: を使用して PlaceEditComponent を登録します。
{ path: 'places/:id', component: PlaceEditComponent, },
編集する場所を取得する
私の最初の解決策は、サービス、エフェクト、ルーター、アクティブ化されたルートの組み合わせです。いくつかの場所に make add ロジックが必要になります。
places サービスにメソッドを追加します。
リッスンアクション
成功を設定して、選択した場所の状態を更新します。
edit-place.component 内の選択した場所を読み取ります。
まず、places.service.ts に getById メソッドを追加します。ID を使用して場所を取得します。
getById(id: string): Observable<Place> { return this.http.get<Place>(`${environment.menorcaPlacesAPI}/${id}`); }
次に、getById を処理する新しいアクションを追加し、places.actions.ts を開いて、編集するアクション、成功と失敗を追加します。
// PlacePageActions 'Edit Place': props<{ id: string }>(), // PlacesApiActions 'Get Place Success': props<{ place: Place }>(), 'Get Place Failure': props<{ message: string }>(),
これらのアクションを処理するためにリデューサーを更新します:
on(PlacesApiActions.getPlaceSuccess, (state, { place }) => ({ ...state, loading: false, placeSelected: place, })), on(PlacesApiActions.getPlaceFailure, (state, { message }) => ({ ...state, loading: false, message, })),
place.Effects.ts を開き、editPlace アクションをリッスンする新しいエフェクトを追加し、placeService.getById を呼び出して、getPlaceSuccess アクションをディスパッチするための応答を取得します。
export const getPlaceEffect$ = createEffect( (actions$ = inject(Actions), placesService = inject(PlacesService)) => { return actions$.pipe( ofType(PlacesPageActions.editPlace), mergeMap(({ id }) => placesService.getById(id).pipe( map((apiPlace) => PlacesApiActions.getPlaceSuccess({ place: apiPlace }) ), catchError((error) => of(PlacesApiActions.getPlaceFailure({ message: error })) ) ) ) ); }, { functional: true } );
この解決策は有望に思えます。 /places:id ルートに移動するには、editPlace アクションをディスパッチし、place-card.component.ts にルーターを挿入する必要があります。
goEditPlace(id: string) { this.store.dispatch(PlacesPageActions.editPlace({ id: this.place().id })); this.router.navigate(['/places', id]); }
効果あります!しかし、いくつかの副作用もあります。別の場所を選択してページに戻ると、選択内容が更新されず、前の選択内容が読み込まれる可能性があります。また、接続が遅い場合は、読み込み中のため「見つからない」エラーが発生する可能性があります。
?Jörgen de Groot のおかげで、解決策の 1 つは、ルーターをエフェクトに移動することです。 places.effect.ts ファイルを開き、サービスとルーターを挿入します。 editPlace アクションをリッスンしてデータを取得し、アクションをナビゲートしてディスパッチします。
最終的なコードは次のようになります:
export const getPlaceEffect$ = createEffect( ( actions$ = inject(Actions), placesService = inject(PlacesService), router = inject(Router) ) => { return actions$.pipe( ofType(PlacesPageActions.editPlace), mergeMap(({ id }) => placesService.getById(id).pipe( tap(() => console.log('get by id')), map((apiPlace) => { router.navigate(['/places', apiPlace.id]); return PlacesApiActions.getPlaceSuccess({ place: apiPlace }); }), catchError((error) => of(PlacesApiActions.getPlaceFailure({ message: error })) ) ) ) ); }, { functional: true } );
ユーザーが場所のリストをクリックしたときのみナビゲートするが、ページをリロードすると機能しないという問題を修正しました。これは、新しいルートでの状態の準備ができていないためですが、エフェクトを使用するオプションがあります。ライフサイクルフック。
エフェクトのライフサイクル フックを使用すると、エフェクトが登録されたときにアクションをトリガーできるため、loadPlaces アクションをトリガーして状態を準備します。
export const initPlacesState$ = createEffect( (actions$ = inject(Actions)) => { return actions$.pipe( ofType(ROOT_EFFECTS_INIT), map((action) => PlacesPageActions.loadPlaces()) ); }, { functional: true } );
エフェクトのライフサイクルと ROOT_EFFECTS_INIT について詳しく読む
はい、状態の準備はできましたが、URL 状態から ID を取得するときにまだ問題が発生しています。
簡単な解決策は、ngOnInit で activeRoute を読み取ることです。 ID が存在する場合は、アクション editPlace をディスパッチします。これにより、selectedPlace 状態がリダイレクトされて設定されます。
そこで、PlaceEditComponent に再度 activateRoute を挿入し、ngOnInit にロジックを実装します。
コードは次のようになります:
export class PlaceEditComponent implements OnInit { store = inject(Store); place$ = this.store.select(PlacesSelectors.selectPlaceSelected); activatedRoute = inject(ActivatedRoute); ngOnInit(): void { const id = this.activatedRoute.snapshot.params['id']; if (id) { this.store.dispatch(PlacesPageActions.editPlace({ id })); } } }
It works! Finally, we add a cancel button to redirect to the places route and bind the click event to call a new method, cancel.
<button (click)="cancel()" class="button is-light" type="reset">Cancel</button>
Remember to inject the router to call the navigate method to the places URL. The final code looks like this:
export class PlaceEditComponent implements OnInit { store = inject(Store); place$ = this.store.select(PlacesSelectors.selectPlaceSelected); activatedRoute = inject(ActivatedRoute); router = inject(Router); ngOnInit(): void { const id = this.activatedRoute.snapshot.params['id']; if (id) { this.store.dispatch(PlacesPageActions.editPlace({ id })); } } cancel() { router.navigate(['/places']); } }
Okay, it works with all features, but our component is handling many tasks, like dispatching actions and redirecting navigation. What will happen when we need more features? We can simplify everything by using NgRx Router, which will reduce the amount of code and responsibility in our components.
Why NgRx Router Store ?
The NgRx Router Store makes it easy to connect our state with router events and read data from the router using build'in selectors. Listening to router actions simplifies interaction with the data and effects, keeping our components free from extra dependencies like the router or activated route.
Router Actions
NgRx Router provide five router actions, these actions are trigger in order
ROUTER_REQUEST: when start a navigation.
ROUTER_NAVIGATION: before guards and revolver , it works during navigation.
ROUTER?NAVIGATED: When completed navigation.
ROUTER_CANCEL: when navigation is cancelled.
ROUTER_ERROR: when there is an error.
Read more about ROUTER_ACTIONS
Router Selectors
It helps read information from the router, such as query params, data, title, and more, using a list of built-in selectors provided by the function getRouterSelectors.
export const { selectQueryParam, selectRouteParam} = getRouterSelectors()
Read more about Router Selectors
Because, we have an overview of NgRx Router, so let's start implementing it in the project.
Configure NgRx Router
First, we need to install NgRx Router. It provides selectors to read from the router and combine with other selectors to reduce boilerplate in our components.
In the terminal, install ngrx/router-store using the schematics:
ng add @ngrx/router-store
Next, open app.config and register routerReducer and provideRouterStore.
providers: [ ..., provideStore({ router: routerReducer, home: homeReducer, places: placesReducer, }), ... provideRouterStore(), ],
We have the NgRx Router in our project, so now it's time to work with it!
Read more about install NgRx Router
Simplify using NgRx RouterSelectors
Instead of making an HTTP request, I will use my state because the ngrx init effect always updates my state when the effect is registered. This means I have the latest data. I can combine the selectPlaces selector with selectRouterParams to get the selectPlaceById.
Open the places.selector.ts file, create and export a new selector by combining selectPlaces and selectRouteParams.
The final code looks like this:
export const { selectRouteParams } = getRouterSelectors(); export const selectPlaceById = createSelector( selectPlaces, selectRouteParams, (places, { id }) => places.find((place) => place.id === id), ); export default { placesSelector: selectPlaces, selectPlaceSelected: selectPlaceSelected, loadingSelector: selectLoading, errorSelector: selectError, selectPlaceById, };
Perfect, now it's time to update and reduce all dependencies in the PlaceEditComponent, and use the new selector PlacesSelectors.selectPlaceById. The final code looks like this:
export class PlaceEditComponent { store = inject(Store); place$ = this.store.select(PlacesSelectors.selectPlaceById); }
Okay, but what about the cancel action and redirect? We can dispatch a new action, cancel, to handle this in the effect.
First, open places.action.ts and add the action 'Cancel Place': emptyProps(). the final code looks like this:
export const PlacesPageActions = createActionGroup({ source: 'Places', events: { 'Load Places': emptyProps(), 'Add Place': props<{ place: Place }>(), 'Update Place': props<{ place: Place }>(), 'Delete Place': props<{ id: string }>(), 'Cancel Place': emptyProps(), 'Select Place': props<{ place: Place }>(), 'UnSelect Place': emptyProps(), }, });
Update the cancel method in the PlacesComponent and dispatch the cancelPlace action.
cancel() { this.#store.dispatch(PlacesPageActions.cancelPlace()); }
The final step is to open place.effect.ts, add the returnHomeEffects effect, inject the router, and listen for the cancelPlace action. Use router.navigate to redirect when the action is dispatched.
export const returnHomeEffect$ = createEffect( (actions$ = inject(Actions), router = inject(Router)) => { return actions$.pipe( ofType(PlacesPageActions.cancelPlace), tap(() => router.navigate(['/places'])), ); }, { dispatch: false, functional: true, }, );
Finally, the last step is to update the place-card to dispatch the selectPlace action and use a routerLink.
<a (click)="goEditPlace()" [routerLink]="['/places', place().id]" class="button is-info">Edit</a>
Done! We did it! We removed the router and activated route dependencies, kept the URL parameter in sync, and combined it with router selectors.
Recap
I learned how to manage state using URL parameters with NgRx Router Store in Angular. I also integrated NgRx with Angular Router to handle state and navigation, keeping our components clean. This approach helps manage state better and combines with Router Selectors to easily read router data.
Source Code: https://github.com/danywalls/start-with-ngrx/tree/router-store
Resources: https://ngrx.io/guide/router-store
以上がNgRx ルーター ストアを使用した Angular ルーター URL パラメーターの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

Web開発におけるJavaScriptの主な用途には、クライアントの相互作用、フォーム検証、非同期通信が含まれます。 1)DOM操作による動的なコンテンツの更新とユーザーインタラクション。 2)ユーザーエクスペリエンスを改善するためにデータを提出する前に、クライアントの検証が実行されます。 3)サーバーとのリフレッシュレス通信は、AJAXテクノロジーを通じて達成されます。

現実世界でのJavaScriptのアプリケーションには、フロントエンドとバックエンドの開発が含まれます。 1)DOM操作とイベント処理を含むTODOリストアプリケーションを構築して、フロントエンドアプリケーションを表示します。 2)node.jsを介してRestfulapiを構築し、バックエンドアプリケーションをデモンストレーションします。

JavaScriptエンジンが内部的にどのように機能するかを理解することは、開発者にとってより効率的なコードの作成とパフォーマンスのボトルネックと最適化戦略の理解に役立つためです。 1)エンジンのワークフローには、3つの段階が含まれます。解析、コンパイル、実行。 2)実行プロセス中、エンジンはインラインキャッシュや非表示クラスなどの動的最適化を実行します。 3)ベストプラクティスには、グローバル変数の避け、ループの最適化、constとletsの使用、閉鎖の過度の使用の回避が含まれます。

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

開発環境におけるPythonとJavaScriptの両方の選択が重要です。 1)Pythonの開発環境には、Pycharm、Jupyternotebook、Anacondaが含まれます。これらは、データサイエンスと迅速なプロトタイピングに適しています。 2)JavaScriptの開発環境には、フロントエンドおよびバックエンド開発に適したnode.js、vscode、およびwebpackが含まれます。プロジェクトのニーズに応じて適切なツールを選択すると、開発効率とプロジェクトの成功率が向上する可能性があります。

CとCは、主に通訳者とJITコンパイラを実装するために使用されるJavaScriptエンジンで重要な役割を果たします。 1)cは、JavaScriptソースコードを解析し、抽象的な構文ツリーを生成するために使用されます。 2)Cは、Bytecodeの生成と実行を担当します。 3)Cは、JITコンパイラを実装し、実行時にホットスポットコードを最適化およびコンパイルし、JavaScriptの実行効率を大幅に改善します。

JavaScriptは、Webサイト、モバイルアプリケーション、デスクトップアプリケーション、サーバー側のプログラミングで広く使用されています。 1)Webサイト開発では、JavaScriptはHTMLおよびCSSと一緒にDOMを運用して、JQueryやReactなどのフレームワークをサポートします。 2)ReactNativeおよびIonicを通じて、JavaScriptはクロスプラットフォームモバイルアプリケーションを開発するために使用されます。 3)電子フレームワークにより、JavaScriptはデスクトップアプリケーションを構築できます。 4)node.jsを使用すると、JavaScriptがサーバー側で実行され、高い並行リクエストをサポートします。
