What I am trying to achieve?
- I have multiple components having almost same checks and data manipulation.. I wanted to shift them in a observable..
- I created an observable name "getData" in my service...
- the twist is "getdata" has a if check.. -> if the local storage has data then return data. if not then request data from api call(getbyid) then manipulate it and return data..
NOTE: we can't change the getbyid(). and they both are in 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()
}
}
}