使用NGRX时如何避免不必要的API调用
我有一个带有2个菜单项的应用程序;团队,球员。每当我之间切换它们时,即使我在存储中有数据,我也必须不必要的API调用。
以下是效果文件: //auth.effects.ts
loadTeams$ = createEffect(() => {
return this.actions$.pipe(
ofType(AuthActions.loadTeams),
switchMap((action) =>
this.apiService.teams$.pipe(
tap(() => console.log('get teams request')),
map((teams: Team[]) => AuthActions.loadTeamsSuccess({ teams })),
catchError((error) => {
console.log('err', error);
return of(AuthActions.loadFailure({ error }));
})
)
)
);
});
以下是我将API呼叫
teams-list.component.ts
export class TeamsListComponent implements OnInit {
loading$?: Observable<boolean>;
error$?: Observable<string>;
teams$?: Observable<Team[]>;
retrySubject$ = new BehaviorSubject<boolean>(true);
constructor(private store: Store<State>) {}
ngOnInit(): void {
this.store.dispatch(loadTeams());
this.teams$ = this.store.select(getTeams);
this.error$ = this.store.select(getError);
this.loading$ = this.store.select(getLoading);
}
fetchRetry() {
this.retrySubject$.next(false);
}
}
在ngoninit中进行的组件,导致不必要的API调用。 this.teams $ = this.store.select(getTeams);
如何预防它,以便在初始化应用程序时使API一次调用?
I have an application with 2 menu item; Teams, Players. Whenever I toggle between them, I have to unnecessary api call even though I have the data in store.
Below is the effects file:
//auth.effects.ts
loadTeams$ = createEffect(() => {
return this.actions$.pipe(
ofType(AuthActions.loadTeams),
switchMap((action) =>
this.apiService.teams$.pipe(
tap(() => console.log('get teams request')),
map((teams: Team[]) => AuthActions.loadTeamsSuccess({ teams })),
catchError((error) => {
console.log('err', error);
return of(AuthActions.loadFailure({ error }));
})
)
)
);
});
Below is the component from which I make api call
teams-list.component.ts
export class TeamsListComponent implements OnInit {
loading$?: Observable<boolean>;
error$?: Observable<string>;
teams$?: Observable<Team[]>;
retrySubject$ = new BehaviorSubject<boolean>(true);
constructor(private store: Store<State>) {}
ngOnInit(): void {
this.store.dispatch(loadTeams());
this.teams$ = this.store.select(getTeams);
this.error$ = this.store.select(getError);
this.loading$ = this.store.select(getLoading);
}
fetchRetry() {
this.retrySubject$.next(false);
}
}
This line in ngOnInit cause unnecessary api call. this.teams$ = this.store.select(getTeams);
How can I prevent it so that it makes the api call one time when initializing the app?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在收到活动后阅读商店,然后过滤掉已经在商店中具有值的发出。
更多信息: https://timdeschryver.dev/blog/start-using-ngrx-effects-for-this/#enhance-your-actor-with-with-with-global-store-state
Read the store after receiving the event, then filter out emits that already have a value in the store.
More info: https://timdeschryver.dev/blog/start-using-ngrx-effects-for-this/#enhance-your-action-with-global-store-state