当我们构建带有状态的应用程序时,入口点是初始化组件状态的关键,但有时,我们需要在 URL 中保留应用程序状态以允许用户添加书签或分享特定的应用程序状态,目的是改善用户体验并简化导航。
大多数情况下,我们在组件中结合 Angular Router 和 ActivatedRoute 来解决这些情况,并将此责任委托给组件,或者在其他情况下,在组件和效果之间进行混合来尝试解决它。
我将继续在梅诺卡岛度假,所以今天早上我学习和练习了如何处理 Angular 路由器中的状态,以及 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
克隆 repo 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, },
我的第一个解决方案是服务、效果、路由器和激活路由的组合。它将需要在多个地方添加逻辑。
在地点服务中添加方法。
聆听动作
设置成功更新所选地点的状态。
读取 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 操作,调用placesService.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 } );
这个解决方案看起来很有前途。我需要调度 editPlace 操作并将路由器注入 place-card.component.ts 以导航到 /places:id 路由。
goEditPlace(id: string) { this.store.dispatch(PlacesPageActions.editPlace({ id: this.place().id })); this.router.navigate(['/places', id]); }
它有效!但也有一些副作用。如果您选择另一个位置并返回页面,则选择可能不会更新,您可以加载上一个位置。此外,如果连接速度较慢,您可能会收到“未找到”错误,因为它仍在加载。
?感谢 Jörgen de Groot,一个解决方案是将路由器移至效果器。打开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 } );
了解有关 Effect 生命周期和 ROOT_EFFECTS_INIT 的更多信息
好的,我已准备好状态,但从 URL 状态获取 ID 时仍然遇到问题。
一个快速修复方法是读取 ngOnInit 中的activatedRoute。如果 id 存在,则分派操作 editPlace。这将重定向并设置 selectedPlace 状态。
所以,在PlaceEditComponent中再次注入activatedRoute,并在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.
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
以上是使用 NgRx 路由器存储的 Angular 路由器 URL 参数的详细内容。更多信息请关注PHP中文网其他相关文章!