问题
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>
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.
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?
回答1:
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}] => {
...
})
)
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));
}
}
For the (the best?) UX you can also use ghost elements - Great User Experiences with Ghost Elements by Thomas Burleson.
来源:https://stackoverflow.com/questions/57508961/ngrx-get-value-from-the-store-before-load-page