那么,让我们了解一些背景信息。在我的例子中,我有可能在主要出口中有多个参数,以及有一个带有参数的辅助路由的可能性。
示例路线:/user/lgxAXtn...h2/home(modal:items/0fn...Z83)
所以,我想出的解决方案是创建所有参数的集合。首先,我们需要打破递归以减少混乱(至少对我而言)
traverse(root: ActivatedRouteSnapshot): Params {
// The object to be returned
let params: Params = {};
// The starting point
let route = root;
// Iterate til we hit the end
while (route.firstChild) {
route = route.firstChild;
// Collect all params on the way there (if any)
params = { ...params,...route.params };
}
return params;
}
现在,这完成了大部分繁重的工作,但我们还没有完全完成。
serialize(routerState: RouterStateSnapshot): RouterReducer.State {
// Since we want an object,we can just reduce the array.
// root.children provides primary and modal outlets
const params = routerState.root.children.reduce(
(acc,curr) => ({ ...acc,...this.traverse(curr) }),{}
);
// Full url
const { url } = routerState;
return { url,params };
}
结果?
state: {
url: '/user/lgxAXtn...h2/home(modal:items/0fn...Z83)',params: {
userId: 'lgxAXtn...h2',itemId: '0fn...Z83'
}
}
这是我想出的更有趣的小解决方案之一,到目前为止它一直对我很好。如果您在使用此方法时遇到任何问题,请告诉我!
完整的serializer.ts
import {
ActivatedRouteSnapshot,Params,RouterStateSnapshot
} from '@angular/router';
import { RouterStateSerializer } from '@ngrx/router-store';
import * as RouterReducer from '../reducers/router.reducer';
export class ParamSerializer
implements RouterStateSerializer<RouterReducer.State> {
private traverse(root: ActivatedRouteSnapshot): Params {
// The object to be returned
let params: Params = {};
// The starting point
let route = root;
// Iterate til we hit the end
while (route.firstChild) {
route = route.firstChild;
// Collect all params on the way there (if any)
params = { ...params,...route.params };
}
return params;
}
serialize(routerState: RouterStateSnapshot): RouterReducer.State {
// Since we want an object,we can just reduce the array.
// root.children provides primary and modal outlets
const params = routerState.root.children.reduce(
(acc,{}
);
// Full url
const { url } = routerState;
return { url,params };
}
}
现在,在我的实例中,我将它用于参数 - 获取段只是一点点修改。类似于 route.url
而不是 traverse 函数中的 route.params。
本文链接:https://www.f2er.com/3094066.html