ok, I have the following method in an angular-cli service, I use it to update a table in "real time", pipe and tap, they work as I want, the bad thing is that it makes the http.get request constantly and obviously that's what it does which exploits the memory of the browser. I know that I can make a POST method and add the pipe and tap there, I add a button in my interface to add a new record and it is updated in real time (that works and is ideal). Unfortunately the http.POST method I use is in .dart / flutter. That is why I use pipe and tap in my angular http.GET getOrders method, so I find myself observing the changes, but what I want is to observe the changes as long as there is one. But what is happening is that this making call after call to the API asking if another new record was added, if it is correct it updates the view. How do I solve that?
control-de-carga-service.ts
private _refresh$ = new Subject<void>();
get refresh$(){
return this._refresh$;
}
getPedidos():Observable<any>{
let headers = new HttpHeaders().set('Content-Type','application/x-www-form-urlencoded');
return this._http.get(this.url 'control-de-carga/pedidos',{headers: headers})
.pipe(
tap(() => {
this._refresh$.next();
})
);
}
and pedidos-linea.component.ts
ngOnInit(): void {
this.getPedidos();
this.subscription = this._controlCargaService.refresh$.subscribe(()
=> {
this.getPedidos();
})
}
getPedidos(): void {
this._controlCargaService.getPedidos().subscribe(
(res) =>{
this.pedidos_list = res;
console.log(res);
},
(err) => console.error(err)
);
}
CodePudding user response:
You've made an infinite loop, subscribing to getPedidos()
calls refresh$.next()
which then calls getPedidos()
which then calls refresh$.next()
etc...
HttpClient
makes a single request and then completes the observable. Normally you would tie this request to an event like a refresh button, or make a request at a certain time interval. In your case you've just created an infinite loop where every time you receive a response, you immediately make another request.
If you want your backend to ping your front end on change then your backend needs to be able to open a web socket, so the client and backend can remain connected. You're going to have to do some research on that and apply it to your specific case.
Here's some resources to get you started:
https://indepth.dev/tutorials/angular/how-to-implement-websockets-in-angular-project https://javascript-conference.com/blog/real-time-in-angular-a-journey-into-websocket-and-rxjs/ https://docs.flutter.dev/cookbook/networking/web-sockets
CodePudding user response:
I think that if you want to do things in real time the best solution is work with websokcets instead of HTTP requests.
The other solution you could execute the method every N amount of seconds (of course, in this case it wont be on real time but will look like as real time).
Hope I helped you!