Tips for achieving asynchronous data retrieval using Angular Observable inside another Observable

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()
    }

    }
     
  }

Answer №1

class DataRetriever_ {
  information: Subject;

  dataRetriever() {
    this.information = new Subject({});
  }

  fetchData(origin: any, id: number): Observable<any> {
    if (origin === 'landing page') {
      const storage = this._crypt.getItem('storage');

      if (!storage) {
        console.log('before fetching');

        const result = this.getById(id).subscribe(result => {
          console.log('result', result);
          this.information.next(result);
        });
        console.log('after fetching');
      } else {
        this.information.next({ info: details });
        
      }
    }
    return this.information.asObservable();
  }
}

Answer №2

To ensure the synchronization of data from observables, it is essential to return an observable and make it wait for the necessary information.

For further details, please refer to: wait observable for other observable in it to respond. Angular async

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can an Angular Application be created in Azure without using an App Service Plan?

Our client has chosen Azure for their custom app development, utilizing API App for the backend and Angular for the front end. Interestingly, they have opted to not use an App Service Plan for the front end. Can anyone provide insight on how an Angular f ...

Unable to locate a suitable version for internal-slot@^1.0.3 at this time

I'm encountering an issue with the npm installation process. When attempting to run npm install on my Angular application, I received an error message that is shown in the image above : No matching version found for internal-slot@^1.0.3 I att ...

Utilizing Angular to import an SVG file from a backend and incorporate its content as a template

I am looking for a solution to load an SVG date from my Spring Boot backend and utilize it as an Angular template. Currently, the request is structured like this: getSVG (): Observable <any> { return this.http.get(`${environment.apiUrl}/path ...

Issue: The function "MyDocument.getInitialProps()" needs to return an object containing an "html" prop with a properly formatted HTML string

Check out my project on GitHub at https://github.com/Talita1996/NLW4 To start the project, I used the command yarn create next-app project_name I made changes to some files by modifying their extensions and adding new code Next, I added typescript to the ...

Why is webpack attempting to package up my testing files?

In my project, I have two main directories: "src" and "specs". The webpack configuration entrypoint is set to a file within the src directory. Additionally, the context of the webpack config is also set to the src directory. There is a postinstall hook in ...

Steps for transforming a complex nested object into an observable and extracting specific values

First of all, I'm wondering if this is the recommended approach in Angular. Can I achieve this?: I have a JSON object with multiple levels of children and I need to console.log specific subsubsubsubchildren. Here is the code I tried: const observable1 ...

Run a single feature file in Protractor by utilizing a specific tag

Is it possible to run just one feature file in Protractor? I am aware that I can specify the file in protractor.conf.js, but I have come across a different solution involving the use of a tag: To single out a specific feature file, you would include a tag ...

Having trouble installing Angular Material due to a getaddrinfo ENOTFOUND error?

When attempting to execute ng add @angular/material in my Angular project, I encountered the following error: Unable to fetch package metadata: request to http://registry.npmjs.org/@angular%2fmaterial failed, reason: getaddrinfo ENOTFOUND proxy.{companyna ...

Sharing an application variable across all components in Angular - Tips and Tricks

I am currently working on a project using Angular7 for the frontend and Flask for the backend. My goal is to subscribe to a service, retrieve the data it returns, save it as an object type variable within my main AppComponent, and then access this variable ...

Encounter a hiccup while installing Angular CLI with NPM

I encountered an issue while trying to install Angular CLI on my local desktop due to a JAVA path error. Despite attempting to install Angular CLI with and without Java, I still face difficulties in the installation process. Error Message: C:\Users& ...

Inoperative due to disability

Issue with Disabling Inputs: [disabled] = true [disabled] = "isDisabled" -----ts > ( isDisabled=true) Standard HTML disabler disable also not functioning properly [attr.disabled] = true [attr.disabled] = "isDisabled" -----ts > ( isDisabled=true) I am a ...

Can you explain the concept of System.register in a JavaScript file?

Can you explain the purpose of System.register in a JS file when utilizing directives in Angular 2? ...

Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning ...

Browser not reflecting changes made to Angular 2 code

Currently facing a challenging issue with my express/angular2 app. Despite using nodemon and seeing the Express code updating fine, I am experiencing issues where my components and services are not updating when I reload the page in the browser. Even aft ...

What specific element is being targeted when a directive injects a ViewContainerRef?

What specific element is associated with a ViewContainerRef when injected into a directive? Take this scenario, where we have the following template: template `<div><span vcdirective></span></div>` Now, if the constructor for the ...

Determining the inner type of a generic type in Typescript

Is there a way to retrieve the inner type of a generic type in Typescript, specifically T of myType<T>? Take this example: export class MyClass { myMethod(): Observable<{ prop1: string, ... }> { .... } } type myClassReturn = ReturnTy ...

Getting started with testing in Angular 2

When I first started coding my app, unit tests were not on my mind. Now, I realize the importance and need to write them. However, while attempting to write tests using Jasmine only, I encountered an error when trying to import components - "system is no ...

Using the ternary operator will always result in a TRUE outcome

Having trouble with a ternary operator expression. AssociatedItemType.ExRatedTag ? session?.data.reloadRow(ids) : this.reloadItemRows(this.prepareItemsIdentities(ids)!), The AssociatedItemType is an enum. I've noticed that const ? 1 : 2 always retur ...

What is the proper way to bind data next to a string in Angular?

I am facing an issue with two variables that are supposed to form a link for an image. I have tried putting them in the src tag using the following code snippet: [src] = {{part1}}+"_"+{{part2}} However, this approach is not working as expected. The scr ...

Angular 10 encounters difficulties when attempting to execute HttpClient

I encountered an error when attempting to execute "ng build". The error message states: ERROR in node_modules/@angular/common/http/http.d.ts:81:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class. ...