首页 > 解决方案 > 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()在订阅者上运行的函数,但它不会重新获取,只需使用相同的数据重新运行该函数。

标签: angulartypescriptrxjs

解决方案


推荐阅读