Using Angular Resource API together with Signals and multiple Requests

Discussão em 'Angular' iniciado por IEE1394, Dezembro 16, 2024.

  1. IEE1394

    IEE1394 Guest

    i have setup where i fire a request to the backend and provide with the request the query params pageSize and pageIndex to the backend. The Page parameters are controlled by a PageEvent.

    So in the old world that looks like

    reloading: boolean = false
    pageSize: number = 20
    pageIndex: number = 0
    totalSize: number = 0
    accounts: AccountSearchEntry[] = []

    request = new AccountSearchRequest('')

    search() {
    this.reload(0, this.pageSize)
    }

    private reload(page: number, size: number) {
    if (this.reloading) return
    this.reloading = true
    this.searchService.searchAccounts(this.request, page, size).subscribe(
    {
    next: value => this.handleData(value),
    error: e => this.handleError(e)
    }
    )
    }


    private handleData(response: AccountSearchResponse) {
    let p = response.result
    this.accounts = p.content
    this.pageSize = p.pageable.size
    this.pageIndex = p.pageable.number
    this.totalSize = p.totalSize
    this.reloading = false
    }


    So far so good. No i want to switch to signals. So i changed it like that.

    pageSize = signal<number>(20)
    pageIndex = signal<number>(0)
    totalSize = signal<number>(0)
    fullTextSearch = signal<string>('')

    accountsCriteria = computed(() => ({
    request: new AccountSearchRequest(this.fullTextSearch()),
    pageSize: this.pageSize(),
    pageIndex: this.pageIndex()
    }))

    accountsResource = resource({
    request: this.accountsCriteria,
    loader: (param) => {
    return toPromise(this.searchService.searchAccounts(param.request.request, param.request.pageIndex, param.request.pageSize), param.abortSignal)
    }
    });

    reloading = this.accountsResource.isLoading
    accounts = computed(() => this.accountsResource.value ?? [])


    the problem comes if i want so reset the page index if i set the fullTextSearch like so

    setFullTextSearch(val: string) {
    this.pageIndex.set(0)
    this.fullTextSearch.set(val)
    }


    because that fires two requests to the backend, what i do not want. Also handling the PageEvent is now difficult

    handlePageEvent(event: PageEvent) {
    // this.reload(event.pageIndex, event.pageSize)
    this.pageIndex.set(event.pageIndex)
    this.pageSize.set(event.pageSize)
    }


    I had the idea to introduce a second criteria for the page and one for the request, but that seems not practival eigher. Also i like to update the pageSize and the pageIndex from both sides. If there is a change on the UI the page size should change and a request will be fired to the backend. But if the backend returns a value, the page size is overwritten with the data provided by the backend.

    Any help appreciated Thx Oli

    Continue reading...

Compartilhe esta Página