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()
}
}
}
CodePudding user response:
class dataFetcher_ {
data: BehaviorSubject;
dataFetcher() {
this.data = new BehaviorSubject({});
}
getdata(origin: any, id: number): Observable<any> {
if (origin === 'main page') {
const localstorage = this._aes.getItem('localstorage');
if (!localstorage) {
console.log('before api');
const res = this.getbyid(id).subscribe(res => {
console.log('res', res);
this.data.next(res);
});
console.log('after api');
} else {
this.data.next({ data: payload });
}
}
return this.data.asObservable();
}
}
CodePudding user response:
we need to return an observable to make it wait for the data from observable.
Reference: wait observable for other observable in it to respond. Angular async