angular - Angular 存储在 RxJS 的时间间隔内重新获取数据
问题描述
我有一个角度存储,它使用 RXJS 在间隔内重新获取数据以更新我的组件的状态。目前我商店的代码如下所示。
leaderboard.store.ts
@Injectable()
export class LeaderboardStore extends Store<LeaderboardStoreState> implements OnDestroy {
private storeRequestStateUpdater: StoreRequestStateUpdater;
private ngUnsubscribe$: Subject<undefined> = new Subject();
private reloadLeaderboards$: Subject<CompetitionFilteringOptions> = new Subject();
constructor(private endpoint: LeaderboardEndpoint) {
super(new LeaderboardStoreState());
}
init(): void {
this.storeRequestStateUpdater = endpointHelpers.getStoreRequestStateUpdater(this);
this.updateLeaderBoard();
}
updateLeaderBoard(): void {
console.log('reloaded leaderboard') // reaches this consol.log on every trigger
this.reloadLeaderboards$
.pipe(
switchMap((filterBy: CompetitionFilteringOptions) => {
console.log('switch maps') //only reaches this one on the first render of the component
return this.endpoint.listLeaderboards(this.storeRequestStateUpdater, filterBy);
}),
tap((leaderboards: any) => {
//manually set the me attribute to true
//Side effect for testing purposes
const currentUser = leaderboards[0].entries.find(entry => entry.userName === 'legenden420');
currentUser.me = true;
const currentUserPoints = currentUser.points;
console.log(leaderboards[0]);
console.log(currentUserPoints);
this.setState({
...this.state,
leaderboards: leaderboards,
currentUserPoints
});
}),
retry(),
takeUntil(this.ngUnsubscribe$))
.subscribe();
}
在我的组件中,oi 设置了一个间隔,以每 5 秒调用一次从外部 API 获取的函数。
问题是它只在第一次渲染时获取 API,然后只到达第一个 console.log 然后退出。
这是我在组件中的实现
leaderboard.view.ts
ngOnInit() {
//Interval to update leaderboard dynamically
this.timer$ = interval(5000);
console.log('init timer')
this.subscription = this.timer$.subscribe(t => {
console.log('updated nr ' + t)
this.store.init()
});
}
我创建了一个next()
在订阅者上运行的函数,但它不会重新获取,只需使用相同的数据重新运行该函数。
解决方案
推荐阅读
- python - 计算每行数据框中的搜索词
- javascript - 无法启动服务器:Gatsby 应用程序 - 意外的模板字符串
- javascript - JS更改功能仅第一次工作
- javascript - Angular 7 SSR,应用组件 ngOnInit() 多次调用
- python - 大海捞针“gfg 中的编码问题”
- web - 如何沿路由路径移动带有动画的标记?
- azure-sql-database - 将 MSI 令牌传递给 flyway 命令行
- google-apps-script - 如何优化我的 Google Apps 脚本使其不超过最大超时?
- gnuplot - gnuplot 5 多图对齐不向后兼容
- dataframe - DataFrame 定义是惰性求值