KarlB
KarlB

Reputation: 21

Angular - rxResource() - how to react to changes in the database

"The Observable produced by the loader() function will consider only the first emitted value, ignoring subsequent emissions."

What if there are changes in the database?

Doesn't that defeat the purpose of a datastream (where I always get the latest data automatically) if rxResource unsubscribes after receiving the first values?

My goal is to reflect the latest news in my template without having to push a reload button. Traditional subscription-solutions provided that.

How can I get the same behavior with rxResource?

Upvotes: 2

Views: 67

Answers (1)

Naren Murali
Naren Murali

Reputation: 57986

If you want to react to changes in database, you are looking for a push based system, like push notifications using websockets.

Pull vs Push API Architecture - System Design


The angular httpClient and fetch are pull based systems (Simple (HTTP requests)) which cannot react to changes in the database, you have to use a different mechanism for this.

Long and Short polling:

There is this concept known as long polling where a pull based system polls the backend (either for short intervals (short polling) or long intervals (long polling) and update the frontend which gives the impression of the database changes being updated.

To achieve polling using resource API check the below answer:

How to perform polling using angular signals and resource API

About rxResource and resource API:

The rxResource is designed by the angular team, to eagerly loaded asynchronous request (like promise and observable) when the source observables provided inside it are changed.

Take for example this below sample code:

@Injectable({
  providedIn: 'root',
})
export class SomeService {
  http = inject(HttpClient);
  serviceIdSignal: WritableSignal<number> = signal(0);

  rxResource = rxResource({
    request: () => this.serviceIdSignal(),
    loader: ({ request: id }) => {
      return this.http.get(`https://jsonplaceholder.typicode.com/todos/${id}`);
    },
  });
}

The rxResource if used by any component, will immediately load the data with the initial value of the signals inside request (serviceIdSignal) and it will again load the data when the source signals are changed (E.g: on the component we do this.someService.serviceIdSignal.set(15);)

Upvotes: 0

Related Questions