What is my goal?
- I have several components with similar checks and data manipulation activities. I aim to centralize these operations in an observable.
- To do this, I created an observable called "getData" within my service...
- The unique aspect of "getData" is that it includes an if statement: if there is existing data in the local storage, return that data. Otherwise, make an API call (using getbyid) to fetch the data, manipulate it, and then return it..
Please note: The getbyid() function cannot be altered, and both functions are within 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
})
console.log('after api');
}else{
data.next({data:payload})
return data.asObservable()
}
}
}