How to make a request that changes the values according to the return of the api

Asked

Viewed 56 times

0

Hello!

I have to request an api, but the api values change dynamically.

was giving a read on Observables, and I can’t tell what I’m doing wrong

the function is already of the Observable type... but does not update the values... inserir a descrição da imagem aqui

this is my ts:

  getData() {
    this.walletService.getWalletFinancialInformation()
      .subscribe((res) => {
        this.patrimonioAtual = res['financialInformationBean'][0].patrimonioOnline.value;
        this.patrimonioAtual = this.formatNumber(this.patrimonioAtual);
      });
  }

my service:

  getWalletFinancialInformation() {
    return this.httpClient.get('minhaUrlSecreta');
  }

and finally my html:

    <div class="money-daily">
      <span class="button-default">R$ {{ patrimonioAtual }},00</span>
    </div>
  • Do you need the value to be changed periodically in a time interval? Is the first request receiving and displaying the value normally? Which version of Angular is using?

  • ola, I am using angular 7, the first request returns the value correctly, but when the value the api returns is changed, the variable is sent with the initial value

  • Are you making new requests on the API? Because API as a rule is stateless in general, you must re-request for the client to receive the change in value.

  • but with the observable, the exchange should be dynamic?

  • No, the observable sends periodic updates of objects persisted in browser memory, date Storage, etc. For example, you define an object in a global variable, and put an observable in it, all children objects with observable will receive update from the global object, however the global object must request periodically in your API to receive a new value, when you set a value for it, it will shoot for all children who are listening to changes, in case they made a "Subscription" on top of it which is an "observable"

  • If you only have one place in the code to receive this value of the current patrimony it is interesting to fire a periodic event, of type setTimeout(() => { this.getData(); }, 30000); for 30s.

  • but using the timeout or interval can result in a crash of the api

Show 2 more comments

1 answer

1

You can use the operator interval and define an issue period

  getWalletFinancialInformation() {
    return interval(5000).pipe(
      switchMap(() => this.http.get('minhaUrlSecreta')));

https://rxjs.dev/api/index/function/interval

  • hello, this way I’m making requests 5 in 5 sec, this can cause a fall of api.

  • yes, I put as an example, but you can switch to a longer interval

  • either this or websocket

  • never worked with websocket, I will take a look at the documentation to see how I can implement

Browser other questions tagged

You are not signed in. Login or sign up in order to post.