angulartypescriptangular10angular11angular12

wait observable for other observable in it to respond. Angular async


What I am trying to achieve?

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.