How to stop listening for signal changes, but retain the last fetched value in angular...

Discussão em 'Angular' iniciado por Naren Murali, Fevereiro 23, 2025.

  1. Naren Murali

    Naren Murali Guest

    I have been going through the start/stop of resource API and wanted to know if there is a way to achieve a pause like functionality, but that I mean:

    The Resource API should stop listening for signal changes, but retain the last fetched value

    When I stop the resource listener, it emptied the value inside the resource.value(), but I want to use this value in my UI and just stop listening for future signal changes which are present in the request callback of either resource or rxResource.

    Below is my minimal reproducible code along with working Stackblitz, for debugging:

    HTML:


    <div>
    <div>
    Resource Request triggers:
    </div>
    <div>
    <input [(ngModel)]="id" type="number"/>
    </div>
    </div>
    <div>
    @if(![rs.Loading, rs.Reloading].includes(rxResource.status())) {
    {{rxResource.value() | json}}
    } @else{
    Loading...
    }
    </div>
    <hr/>
    <div>
    @if(![rs.Loading, rs.Reloading].includes(resource.status())) {
    {{resource.value() | json}}
    } @else{
    Loading...
    }
    </div>
    <hr/>
    <div>
    <div>Current Status: {{rs[resource.status()]}}</div>
    <button (click)="start()">Start Listening</button>
    <button (click)="pause()">Pause Listening (Retain last value)</button>
    <button (click)="stop()">Stop Listening</button>
    </div>

    TS:


    export class App {
    id = signal(1);
    rs = ResourceStatus;
    http = inject(HttpClient);
    resourceControl = signal(true);
    resourceRequest = (): ResourceRequest | undefined => {
    if (this.resourceControl()) {
    return {
    id: this.id(),
    };
    } else {
    return undefined;
    }
    };
    resource: ResourceRef<any> = resource<ResourceRequest | undefined, any>({
    request: this.resourceRequest,
    loader: ({ request: { id }, abortSignal }) => {
    return fetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {
    signal: abortSignal,
    }).then((res: any) => res.json());
    },
    });
    rxResource: ResourceRef<any> = rxResource<ResourceRequest | undefined, any>({
    request: this.resourceRequest,
    loader: ({ request: { id } }) => {
    return this.http.get<any>(
    `https://jsonplaceholder.typicode.com/todos/${id}`
    );
    },
    });

    start() {
    this.resourceControl.set(true);
    }

    stop() {
    this.resourceControl.set(false);
    }

    pause() {
    // how to pause the resource and stop listening to future changes but retain the last value
    }
    }

    Stackblitz Demo

    Continue reading...

Compartilhe esta Página