How can I reuse a subscribe function to update data, since I need to perform actions after the result of the call in another function? Do I need to do another subscribe? Naturally, I can’t use async/await to make the process wait, I put the code like this because that’s how it was with fetch before.
ngOnInit() {
this.carregaDados();
}
carregaDados() {
this.dataService.getData().subscribe({
next: (res:Result) => {
if(!res.success) {
this.errors.set([res.errors[0]?.message || "Erro desconhecido"]);
}
else {
this.conectar(this.dataService.data);
this.dataFilters = this.dataService.geraObjFiltros();
this.dateTimeUpdatelabel.set(this.dataService.dateTimeUpdateLabel)
}
},
error: (err) => {
console.log('Erro:',err.message)
this.errors.set([err.message]);
}
});
}
async atualizarGrid() {
const estadoGrid = this.datasource.estadoCorrente
await this.carregaDados();
const dataFiltered = this.dataService.goFilterFinal();
this.conectar(dataFiltered);
this.datasource.ordenacao = estadoGrid.ordenacao;
this.datasource.tamanhoPagina = estadoGrid.tamanhoPagina;
this.datasource.pagina = estadoGrid.pagina;
console.log(this.datasource.estadoCorrente)
}
atualizarGridAnotherSubscribe() {
this.dataService.getData().subscribe(
(result:Result) => {
const estadoGrid = this.datasource.estadoCorrente
const dataFiltered = this.dataService.goFilterFinal();
this.conectar(dataFiltered);
this.datasource.ordenacao = estadoGrid.ordenacao;
this.datasource.tamanhoPagina = estadoGrid.tamanhoPagina;
this.datasource.pagina = estadoGrid.pagina;
this.dateTimeUpdatelabel.set(this.dataService.dateTimeUpdateLabel);
}
);
}
I subscribed again and repeated the information from the previous subscriber, but it doesn’t seem like the best solution.
3
Really I don’t understand so much the question, but…
When we want to execute some when subscribe we can use a subject, and the rxjs operators startsWith (execute indmediatmy) and switchMap (change one observable to another observable)
dispatcher$!:Subject<any>=new Subject<any>()
ngOnInit()
{
this.dispatcher$.pipe(
startsWith(null),
switchMap(_=>this.mainObservable()
)).subscribe((res:any)=>{
..here we have the response of "mainObservable"..
})
}
In this way, in ngOnInit we execute the mainObservable and execute the actions and also we can do
this.dispatcher$.next(null)
And execute again the “mainObservable”
a little stackblitz (In the example the “mainObservable” is a call to a service.getData())