用于无限滚动的可观察分页以保持最新

我试图让我的 observable 在分页期间自动更新。

仅页面触发器

当调用 load() 时,页面 observable 被触发,但订阅 observable 在更新时不会被触发...

pageSub = new BehaviorSubject<number>(1);
page = 1;

// in constructor...

this.posts = this.pageSub
  .pipe(
    mergeMap((page: number) => this.urql
      .subscription(this.GET_POSTS,{
          first: this.ITEMS.toString(),offset: (this.ITEMS * (page - 1)).toString()
        }
      )
    ),scan((acc,value) => [...acc,...value]),);

// called from button

load() {
  this.page += 1;
  this.pageSub.next(this.page);
}

仅订阅触发器

此处确实触发了订阅更改,但是当调用 load() 时,不会触发页面更改...

this.posts = combineLatest([this.pageSub,this.urql
  .subscription(this.GET_POSTS,{
      first: this.ITEMS.toString(),offset: (this.ITEMS * (this.page - 1)).toString()
    }
  )]).pipe(
    map((arr: any[]) => arr[1])
  );

当然,有一种方法可以让 Observable 通过页面更改和订阅更改来更新吗?

我应该补充一点,重置变量声明 this.posts 不起作用,因为它刷新了页面并且不是预期的行为。

有什么想法吗?

谢谢,

J

xb588172 回答:用于无限滚动的可观察分页以保持最新

明白了:

mainStream: BehaviorSubject<Observable<any>>;

posts!: Observable<any>;

constructor(private urql: UrqlModule) {

  this.mainStream = new BehaviorSubject<Observable<any>>(this.getPosts());

  this.posts = this.mainStream.pipe(mergeAll());

}

async load() {
  this.page += 1;
  this.mainStream.next(this.combine(this.mainStream.value,this.getPosts()));
}

getPosts() {
  return this.urql.subscription(this.GET_POSTS,{
      first: this.ITEMS.toString(),offset: (this.ITEMS * (this.page - 1)).toString()
    }
  )
}

combine(o: Observable<any>,o2: Observable<any>) {
  return combineLatest([o,o2]).pipe(
    map((arr: any) => arr.reduce((acc: any,cur: any) => acc.concat(cur)))
  );
}

本文链接:https://www.f2er.com/717793.html

大家都在问