Issue
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.asObservable()
})
console.log('after api');
}else{
data.next({data:payload})
return data.asObservable()
}
}
}
CURRENT scenario: its just hitting the getbyid and not waiting for the response and proceed... if somehow we make it to wait for the response this can be solved.
Solution
You don't need BehaviorSubject in this kind of scenario. Something like this should work (I supposed "payload" is the content of your storage ?):
getbyid(id: any): Observable<any> {
return this.http.post<any>(this.serverurl, id));
}
getData(origin: any, id: number): Observable<any> {
if (origin !== 'main page') {
return EMPTY;
}
const payload = this._aes.getItem('localstorage');
return payload ? of(payload) : this.getById(id);
}
If payload
is set, we return an observable with it. If not, an observable with a backend call.
In both cases, you have to subscribe from where you call getData
method and wait response.
Answered By - Adrien SAULNIER
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.