Issue
I am having issue with persisting values for an angular component when it is being used multiple times on the page.
I have a angular component which itself has its own service and makes an http call. Now i am going to use this component multiple times on the page, but i want to restrict the http call to happen only once.
For this i tried below code but this doesn't seems to work. Could someone throw some inputs here.
Parent Component HTML
<component-parent>
<child-comp [input1]="xyz" [input2] = "abc"></child-comp>
<div> test content </div>
<div> test content 2 </div>
<child-comp [input1]="111" [input2] = "222"></child-comp>
</component-parent>
child component.ts
this.childCompService.getResults(this.input1, this.input2).subscribe((resp) =>{
//some processing data
})
child Component service.ts
private results = []<any>;
getResults(inp1, inp2):observable<any> {
if (this.results && this.results.length > 0) {
//do not make httpcall
// process results and return
of(this.results)
} else {
this.http.get(url, payload).subscribe((val) => {
this.results = value
})
}
}
Is there a way using RXJS i can persist the http results fetched first time and do not make the call again.
Solution
If it is initialised every time you create a component, save the data in the local storage as a persistent layer. So, every time you make a call check if it exists else call the api :
getResults(inp1, inp2):observable<any>{
const data = localStorage.getItem('results');
if(data){
//do not make httpcall
// process results and return
of(data)
}else{
this.http.get(url, payload).subscribe((val) => {
this.results = val;
localStorage.setItem('results', JSON.stringify(val))
})
}
}
Answered By - Apoorva Chikara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.