Within my table, I have a list of names and an input tag that filters the content of the table when its value changes. The data is retrieved from an HTTP request to a service.
I am encountering three different scenarios:
1- If I subscribe to this.ds.getDrogas()
only in the ngOnInit()
function, the table displays all the content but the filter does not work.
2- If I subscribe to this.ds.getDrogas()
only in the filterName()
function, the table initially appears empty. However, once I change the input value, the filter starts to work correctly. If I delete the input's content, the table shows all the data again, and if I write something new, the filter functions properly.
3- If I subscribe to the observable in both functions, it behaves as expected. The table initially displays all the content, and the filter works correctly when the input value changes.
I am aware that the code within ngOnInit()
is only executed once, but should a subscription continue listening for observable changes?
I would greatly appreciate your assistance.
Service Side:
getDrogas(): Observable <HttpResponses> {
return this.http.get<HttpResponses>(this.apiUrl +'/drogas')
}
Table-Component.ts:
ngOnInit{
this.ds.getDrogas().pipe(
map((data)=> data.data
.filter(element=> element.identificacion.nombre.startsWith(this.contador))))
.subscribe(res=> {this.dataDroga= res; console.log('Ejecutado con valor de contador'+
this.contador)});
}
contador: string =''
filterName(){
this.ds.getDrogas()
console.log(this.dataDroga)
}
Table-Component.html:
<input type="text" [(ngModel)]='contador' (ngModelChange)='filterName()'>