What is my goal?
- I have several components with similar checks and data manipulation tasks. I am looking to centralize these tasks within an observable.
- To achieve this, I created an observable named "getData" in my service...
- The complexity lies in the fact that "getData" includes an if check -> if there is data in the local storage, return it. if not, make an API call (getbyid) to fetch the data, manipulate it, and then return it.
NOTE: The getbyid() function cannot be altered, and both functions reside in the same service.
API
getbyid(id: any): Observable<any> {
return this.http.post<any>(this.serverurl, id )
.pipe(tap((res) => { return res }));
}
MY CODE
getData(origin: any, id:number):Observable<any> {
let data= new BehaviorSubject({});
if(origin=='main page'){
let localstorage= this._aes.getItem('localstorage')
if(!localstorage){
console.log('before api');
this.getbyid(id).subscribe(res=>{
console.log('res',res);
data.next(res)
return data.asObservable()
})
console.log('after api');
}else{
data.next({data:payload})
return data.asObservable()
}
}
}
CURRENT scenario: the code is currently calling getbyid but proceeding without waiting for the response. This could be resolved by ensuring that the code waits for the response before proceeding further.