How to perform polling using angular signals and resource API

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

  1. Naren Murali

    Naren Murali Guest

    I have this scenario, where the database is updated regularly, for example say stock market prices (I do not need immediate updates a poll every 2 minutes is good enough).

    Using short intervals like 2 or 5 seconds will lead to performance issues so I am choosing 2 minutes as my threshold for polling.

    I want to implement a polling mechanism to update the values at the set interval.

    Short and long polling

    I know it can be done with push based systems, but I want to achieve this with push based system.

    Below it the minimal reproducible code and working stackblitz for reference:

    @Component({
    selector: 'app-root',
    imports: [CommonModule],
    template: `
    <div>{{rxResource.value() | json}}</div>
    <hr/>
    <div>{{resource.value() | json}}</div>
    `,
    })
    export class App {
    http = inject(HttpClient);
    serviceIdSignal: WritableSignal<number> = signal(1);
    rxResource = rxResource({
    request: () => this.serviceIdSignal(),
    loader: ({ request: id }) => {
    return this.http.get(`https://jsonplaceholder.typicode.com/todos/${id}`);
    },
    });

    resource = resource({
    request: () => this.serviceIdSignal(),
    loader: ({ request: id }) => {
    return fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(
    (res: any) => res.json()
    );
    },
    });
    }


    The above code does not react/poll, my input signal stays the same, but I need to poll using resource API.

    Stackblitz Demo

    Continue reading...

Compartilhe esta Página