如何从存储中解析数据?



使用路由解析器,我试图从存储中获得如下数据

export class GetActiveCustomerService implements Resolve<any> {
constructor(private store: Store<AppState>) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
return this.store.select('customer').pipe(
first(),
map((data) => {
return data.customer;
})
);
}
}

前一次尝试总是返回null

解析存储在存储中的数据的正确方法是什么?

更新0

这个修改返回预期的结果。但是刷新浏览器时,数据为空。我理解这是因为take(1)。如果这是实现我提到的目标的途径,那么如何使数据在刷新后仍然有效呢?

export class GetActiveCustomerService implements Resolve<any> {
constructor(private store: Store<AppState>) {}
private getActiveCustomer(): Observable<any> {
return this.store.select('customers').pipe(take(1));
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
return this.getActiveCustomer();
}
}

更新1

我找到了这个答案https://stackoverflow.com/a/58711499/615274来自一个和我面临类似问题的人。常用的溶液为take(1)first()。但是在我本地刷新获得的数据时,它变成了null。处理这种情况的正确方法是什么?

Ngrx在重新加载后不保留/保存数据。在刷新页面之前,使用本地存储或cookie保存数据。

我不知道你想达到什么目的。

如果逻辑是能够刷新带有参数(selectedProductId)的页面,然后在组件(ProductDetailComponent)中显示相应的数据,考虑到参数,使用ngrx有两个解决方案:

  • 在您的商店中有一个使用Guard更新的selectedProductId。因此,每次刷新页面时,Guard都会设置selectedProductId,并且您有一个特定的选择器,它将使用selectedProductId来获取适当的数据。
  • 或者使用ngrx/router,它会为你做大部分的工作,并为你的url中的每个参数提供选择器。

显然在这两种情况下你都必须确保:

  • 您调用回调来获取数据,因为当您刷新页面时,所有内容都将从存储中删除。
  • 你的商店中有一个布尔值"isLoaded"它在初始状态被设置为false,当你接收到数据时被设置为true,你在等待数据时显示一个旋转器或任何你想要的东西。

通过使状态再水化来解决问题。在有关属性的配置中,已排除在浏览器的存储中持久化。这导致了下面描述的行为

export function storageSyncReducer(reducer: ActionReducer<AppState>) {
const sync = storageSync<AppState>({
features: [
{ stateKey: 'some' },
{ stateKey: 'another' },
{ stateKey: 'customer' } // <- here it was added
],
rehydrate: true,
storage: window.sessionStorage,
});
return sync(reducer);
}

最新更新