ngrx:在加载页面之前从商店获取价值 [英] ngrx: get value from the store before load page

查看:69
本文介绍了ngrx:在加载页面之前从商店获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有页面组件,在其中显示了 ngrx/store 中的一些数据:

I have page component, inside that I'm displaying some data from ngrx/store:

// profile.ts
user$: User = this.store.select('user')

// profile.html
...

<div *ngIf="user$ | async; let user">
  <div>{{user.id}}</div>  
  <div>{{user.email}}</div>
</div>

这有效,但是我不喜欢它最初加载的页面没有数据,然后在1秒钟后从 user $ 添加此数据.我知道这是应该的-因为我使用的是异步管道,但是我想更改它.

This works, but I don't like that it initially loads the page without data, and then after 1 sec add this data from the user$. I understand this is how it should be - because I'm using async pipe, but I want to change it.

我有什么选择?我能以某种方式从商店中预加载此 user 选择,以将其包含在所有组件中,这样我就不必每次都从商店中请求它们了,因此,加载后从商店中获取一些数据闪烁"?

What options do I have? Can I somehow preload this user selection from the store, to have it in all components, so that I don’t need to request them from the store every time, because of this, all the pages where I get some data from the store "flickering" after loading?

推荐答案

最简单的不获取数据(如果已经在商店中)的方法是在效果内部-

The easiest way to to not fetch data if it's already in the store, would be inside an effect - Start using ngrx/effects for this by myself.

@Effect()
getOrder = this.actions.pipe(
  ofType<GetOrder>(ActionTypes.GetOrder),
  withLatestFrom(action =>
    of(action).pipe(
      this.store.pipe(select(getOrders))
    )
  ),
  filter(([{payload}, orders]) => !!orders[payload.orderId])
  mergeMap([{payload}] => {
    ...
  })
)

但是我认为您正在寻找的是Angular路由器防护,以便在您将数据存储在商店中后就可以获取数据并加载页面.请参阅Todd Motto的使用Route Guards预加载ngrx存储,以获取更多信息.

But I think what you're looking for are Angular router guards to fetch the data and load the page once you have the data in your store. See Preloading ngrx store with Route Guards by Todd Motto for more info.

@Injectable()
export class CoursesGuard implements CanActivate {
  constructor(private store: Store<CoursesState>) {}

  getFromStoreOrAPI(): Observable<any> {
    return this.store
      .select(getCoursesState)
      .do((data: any) => {
        if (!data.courses.length) {
          this.store.dispatch(new Courses.CoursesGet());
        }
      })
      .filter((data: any) => data.courses.length)
      .take(1);
  }

  canActivate(): Observable<boolean> {
    return this.getFromStoreOrAPI()
      .switchMap(() => of(true))
      .catch(() => of(false));
  }
}

对于(最好的?)UX,您还可以使用虚幻元素-使用Ghost Elements的出色用户体验托马斯·伯里森(Thomas Burleson).

For the (the best?) UX you can also use ghost elements - Great User Experiences with Ghost Elements by Thomas Burleson.

这篇关于ngrx:在加载页面之前从商店获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆