Angular Pagination using BehaviorSubject and scan

I’ve been trying to create a pagination.

The HTTP call should be triggered:

  • when the formular has been changed (starting from page zero),
  • when “Load More” button is pressed (button triggers BehaviorSubject loadMore$).

Whenever the button is pressed, new value is emitted with the current count of the results (resultCount). With the help of resultCount I can set the new page number.

Pagination:

pageSize: 10,
resultCount: 0 page will be 0;

but if I trigger load with button:
resultCount: 10, page will be 1

For the merging data from previous http call and current http call I use scan operator, which works also fine.

The problem starts, when I load multiple pages for the same form value and then change the form value again. loadMore$ is not set to 0 and it starts searching from the previous resultCount.

STEPS

  1. Change the person type to Natural (has only 3 results)
  2. Change the person type to different value (with more results, where we can trigger pagination)
  3. Trigger pagination (resultCount will be set to 10)
  4. Change the person type back to Natural
  5. BehaviorSubject does not reset its value, so resultCount is still 10, nothing shows up, as we only have 3 results and we’re asking for page 2 (or simply ignoring first 10 results)
  6. click on the button will fix the problem as it will set resultCount to 0

Bug simulation with the description

import { Component, OnInit } from '@angular/core';
import { ImportsModule } from './imports';
import {
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import {
  BehaviorSubject,
  Observable,
  merge,
  debounceTime,
  switchMap,
  filter,
  of,
  tap,
  scan,
  map,
} from 'rxjs';
import { PersonTypeModel } from './model/person-type.model';

@Component({
  selector: 'dropdown-basic-demo',
  templateUrl: './dropdown-basic-demo.html',
  standalone: true,
  imports: [ImportsModule, ReactiveFormsModule],
})
export class DropdownBasicDemo implements OnInit {
  // separate formGroup as we want to add debounceTime only for subGroup
  formGroup = new FormGroup({
    personType: new FormControl<number | null>(null, Validators.required),
    subGroup: new FormGroup({
      name: new FormControl(''),
      surname: new FormControl(''),
      identificationNumber: new FormControl(''),
    }),
  });

  readonly pageSize = 10;
  result$!: Observable<{ data: PersonTypeModel[]; totalRecords: number }>;
  loadMore$ = new BehaviorSubject<number>(0);

  get formControls() {
    return this.formGroup.controls;
  }
  readonly personTypeOptions = [
    { label: 'Firefighter', id: 1 },
    { label: 'Policeman', id: 2 },
    { label: 'Legal', id: 3 },
    { label: 'Natural', id: 4 },
  ];

  ngOnInit() {
    const personTypeChange$ = this.formControls.personType.valueChanges.pipe(
      tap(() => this.formGroup.updateValueAndValidity()) // update value and validity (without this will be first change mark as invalid)
    );

    // combine two observables
    this.result$ = merge(
      personTypeChange$,
      this.formControls.subGroup.valueChanges.pipe(debounceTime(300))
    ).pipe(
      filter(() => this.formGroup.valid), // person type is required, check
      switchMap(() => {
        return this.loadMore$.pipe(
          switchMap((resultCount) => {
            return this.getPersonByPersonType(resultCount);
          }),
          scan(
            (state, change) => ({
              ...state,
              ...change,
              data: [...(state?.data ?? []), ...(change?.data ?? [])],
            }) // scan previous and current result
          )
        );
      }),
      map((state) => ({
        ...state,
        noMoreRecords: state.totalRecords === state.data.length,
      }))
    );
  }
<form
  [formGroup]="formGroup"
  class="card flex flex-column gap-3 justify-content-center"
>
  <p-dropdown
    [options]="personTypeOptions"
    optionValue="id"
    placeholder="Select person type"
    formControlName="personType"
  />

  <div class="flex gap-3" formGroupName="subGroup">
    <input pInputText placeholder="Name" formControlName="name" type="text" />
    <input
      pInputText
      formControlName="surname"
      placeholder="Surname"
      type="text"
    />
    <input
      pInputText
      formControlName="identificationNumber"
      placeholder="Identification number"
      type="text"
    />
  </div>
</form>

<div *ngIf="result$ | async as result" class="flex flex-column gap-3">
  <div *ngFor="let personType of result?.data">
    {{ personType.name }} {{ personType.surname }} - {{ personType.description
    }}
  </div>

  <button
    pButton
    (click)="loadMore$.next(result?.data?.length)"
    [disabled]="result.noMoreRecords"
  >
    Load More
  </button>
</div>

Here is the simplified stackblitz demo

I’ve tried to fix the problem by emitting new value whenever form changed this.loadMore$.next(0)

and adding debounceTime(1) to this.loadMore$ stream to prevent duplicit HTTP calls.

Here is an updated example

It works, but maybe there is a better solution how to reset behavior subject. Or maybe even create stream in completely different way.

Thanks for any advices!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật