Rumah >hujung hadapan web >tutorial js >Parameter URL Penghala Sudut Menggunakan Kedai Penghala NgRx
Apabila kami membina apl dengan keadaan, titik masuk adalah kunci untuk memulakan keadaan kami untuk komponen kami, tetapi kadangkala, kami mempunyai keperluan untuk mengekalkan keadaan aplikasi dalam URL untuk membolehkan pengguna menanda halaman atau kongsi keadaan aplikasi tertentu, dengan matlamat untuk menambah baik pengalaman pengguna dan memudahkan navigasi.
Kebanyakan kes, kami menggabungkan Penghala Sudut dan ActivatedRoute dalam komponen kami untuk menyelesaikan kes ini dan mewakilkan tanggungjawab ini kepada komponen atau dalam kes lain membuat campuran antara komponen dan kesan untuk mencuba menyelesaikannya.
Saya meneruskan percutian saya di Menorca, jadi saya mengambil masa pagi ini untuk mempelajari dan berlatih cara mengendalikan keadaan dalam Penghala Sudut dan cara penghala ngrx boleh membantu memperbaik kod saya dan mengurangkan tanggungjawab dalam komponen saya.
Saya ingin membuat halaman edit yang membolehkan pengguna mengubah suai butiran tempat yang dipilih, berkongsi URL dan kembali ke keadaan yang sama kemudian. Contohnya, http://localhost/places/2, dengan 2 ialah ID tempat yang sedang diedit. Pengguna juga seharusnya boleh kembali ke halaman utama selepas melakukan tindakan.
?Artikel ini adalah sebahagian daripada siri saya tentang pembelajaran NgRx. Jika anda ingin mengikutinya, sila semaknya.
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
Klon repo mula-dengan-ngrx, projek ini bawa dengan ngrx dan aplikasi sedia dan tukar ke cawangan crud-ngrx
https://github.com/danywalls/start-with-ngrx.git git checkout crud-ngrx
Sudah tiba masanya untuk pengekodan!
Terminal terbuka pertama dan menggunakan CLI Sudut, jana komponen baharu:
ng g c pages/place-edit
Seterusnya, buka app.routes.ts dan daftarkan PlaceEditComponent dengan parameter /places/:id:
{ path: 'places/:id', component: PlaceEditComponent, },
Penyelesaian pertama saya ialah gabungan perkhidmatan, kesan, penghala dan laluan yang diaktifkan. Ia memerlukan penambahan logik di beberapa tempat.
Tambah kaedah dalam perkhidmatan tempat.
Dengar tindakan
tetapkan kejayaan untuk mengemas kini keadaan tempat yang dipilih.
baca tempat yang dipilih dalam edit-place.component.
Mula-mula, tambah kaedah getById dalam places.service.ts, ia mendapatkan tempat dengan menggunakan id.
getById(id: string): Observable<Place> { return this.http.get<Place>(`${environment.menorcaPlacesAPI}/${id}`); }
Seterusnya, tambah tindakan baharu untuk mengendalikan getById, open places.actions.ts tambah tindakan untuk mengedit, kejayaan dan kegagalan:
// PlacePageActions 'Edit Place': props<{ id: string }>(), // PlacesApiActions 'Get Place Success': props<{ place: Place }>(), 'Get Place Failure': props<{ message: string }>(),
Kemas kini pengurang untuk mengendalikan tindakan ini:
on(PlacesApiActions.getPlaceSuccess, (state, { place }) => ({ ...state, loading: false, placeSelected: place, })), on(PlacesApiActions.getPlaceFailure, (state, { message }) => ({ ...state, loading: false, message, })),
Buka place.effects.ts, tambahkan kesan baharu untuk mendengar tindakan editPlace, panggil placesService.getById, dan kemudian dapatkan respons untuk menghantar tindakan 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 } );
Penyelesaian ini nampaknya menjanjikan. Saya perlu menghantar tindakan editPlace dan menyuntik penghala dalam place-card.component.ts untuk menavigasi ke laluan /places:id.
goEditPlace(id: string) { this.store.dispatch(PlacesPageActions.editPlace({ id: this.place().id })); this.router.navigate(['/places', id]); }
Ia berkesan! Tetapi terdapat beberapa kesan sampingan. Jika anda memilih tempat lain dan kembali ke halaman, pilihan mungkin tidak dikemas kini dan anda mungkin memuatkan yang sebelumnya. Selain itu, dengan sambungan perlahan, anda mungkin mendapat ralat "tidak ditemui" kerana ia masih dimuatkan.
?Satu penyelesaian, terima kasih kepada Jörgen de Groot, adalah untuk memindahkan penghala ke kesan. Buka fail places.effect.ts dan suntikan perkhidmatan dan penghala. Dengar tindakan editPlace, dapatkan data, kemudian navigasi dan hantar tindakan itu.
Kod akhir kelihatan seperti ini:
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 } );
Sekarang kami membetulkan isu menavigasi hanya apabila pengguna mengklik dalam senarai tempat, tetapi apabila memuatkan semula halaman bahawa halaman itu tidak berfungsi, kerana negeri kami belum bersedia dalam laluan baharu, tetapi kami mempunyai pilihan untuk menggunakan kesan itu cangkuk kitar hayat.
Kesan cangkuk kitaran hayat membolehkan kami mencetuskan tindakan apabila kesan didaftarkan, jadi saya wan mencetuskan tindakan loadPlaces dan sediakan keadaan.
export const initPlacesState$ = createEffect( (actions$ = inject(Actions)) => { return actions$.pipe( ofType(ROOT_EFFECTS_INIT), map((action) => PlacesPageActions.loadPlaces()) ); }, { functional: true } );
Baca lebih lanjut tentang kitaran hayat Kesan dan ROOT_EFFECTS_INIT
Baiklah, saya sudah sediakan keadaan, tetapi saya masih menghadapi masalah apabila mendapatkan ID daripada keadaan URL.
Pembetulan pantas ialah membaca Laluan yang diaktifkan dalam ngOnInit. Jika id ada, hantar tindakan editPlace. Ini akan mengubah hala dan menetapkan keadaanTempat yang dipilih.
Jadi, suntik activatedRoute sekali lagi dalam PlaceEditComponent dan laksanakan logik dalam ngOnInit.
Kodnya kelihatan seperti ini:
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.
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.
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
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.
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
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.
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
Atas ialah kandungan terperinci Parameter URL Penghala Sudut Menggunakan Kedai Penghala NgRx. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!