angular 具有 ngrx 效果和 take 运算符的解析器
angular resolver with ngrx effect and take operator
我的应用程序中有一个路由使用解析器从数据库中获取数据(对象数组)。
resolve 函数检查存储状态中是否存在数据(如果数组有长度),如果不存在,它会调度一个 effect 从 db 中获取数据并等待该 effect 完成。
fetch effect 调度了一个 "set" effect,它不能通过错误,因为它只是设置了一些值。
我只想获取一次,这样万一用户刷新页面,他仍然可以获得他需要的数据,
但是我的代码一直在尝试获取,因为一开始没有数据。
在我开始玩代码之后,我得到了以下信息:
- 如果我要添加水龙头或第二个 switchMap(水龙头之后的那个),
我得到一个无限循环
- 如果我删除从 "line number 1"(不包括)到 "line number 2"(包括)的行,我不会得到无限循环。
谁能给我解释一下这种行为?
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
return this.store.select('company').pipe(
take(1),
map(comState => {
return comState.comps;
}),
switchMap(comps => {
if(!comps.length){
this.store.dispatch(new CompActions.FetchAll());
return this.actions$.pipe(
ofType(CompActions.SET_ALL),
take(1), //------------ "line number 1"
// tap(() => {
// this.router.navigate([state.url.split('/')[1]]);
// }),
switchMap(actionData => {
const re = /\d+/;
const compInd = re.exec(state.url);
if(compInd && +compInd < actionData['payload']['length']){
return of(actionData['payload']);
}
this.router.navigate([state.url.split('/')[1]]);
})//------------ "line number 2"
);
} else {
return of(comp);
}
})
)
}
您不应从 resolve
块内导航。如果你这样做,守卫会被一次又一次地检查。 Angular 将决定您是否可以导航。您要导航到的路线已在别处声明。
我的应用程序中有一个路由使用解析器从数据库中获取数据(对象数组)。 resolve 函数检查存储状态中是否存在数据(如果数组有长度),如果不存在,它会调度一个 effect 从 db 中获取数据并等待该 effect 完成。
fetch effect 调度了一个 "set" effect,它不能通过错误,因为它只是设置了一些值。
我只想获取一次,这样万一用户刷新页面,他仍然可以获得他需要的数据, 但是我的代码一直在尝试获取,因为一开始没有数据。
在我开始玩代码之后,我得到了以下信息:
- 如果我要添加水龙头或第二个 switchMap(水龙头之后的那个), 我得到一个无限循环
- 如果我删除从 "line number 1"(不包括)到 "line number 2"(包括)的行,我不会得到无限循环。
谁能给我解释一下这种行为?
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
return this.store.select('company').pipe(
take(1),
map(comState => {
return comState.comps;
}),
switchMap(comps => {
if(!comps.length){
this.store.dispatch(new CompActions.FetchAll());
return this.actions$.pipe(
ofType(CompActions.SET_ALL),
take(1), //------------ "line number 1"
// tap(() => {
// this.router.navigate([state.url.split('/')[1]]);
// }),
switchMap(actionData => {
const re = /\d+/;
const compInd = re.exec(state.url);
if(compInd && +compInd < actionData['payload']['length']){
return of(actionData['payload']);
}
this.router.navigate([state.url.split('/')[1]]);
})//------------ "line number 2"
);
} else {
return of(comp);
}
})
)
}
您不应从 resolve
块内导航。如果你这样做,守卫会被一次又一次地检查。 Angular 将决定您是否可以导航。您要导航到的路线已在别处声明。