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 a "fragile export" be generated in TypeScript?

Testing modular code can be challenging when you have to export things just for the purpose of testing, which can clutter your code and diminish the effectiveness of features like "unused variable" flags on compilers or linters. Even if you remove a usage ...

Please convert the code to async/await format and modify the output structure as specified

const getWorkoutPlan = async (plan) => { let workoutPlan = {}; for (let day in plan) { workoutPlan[day] = await Promise.all( Object.keys(plan[day]).map(async (muscle) => { const query = format("select * from %I where id in (%L) ...

I need help figuring out how to showcase the following object in an Angular 5 HTML file

The console screenshot above shows an object with two values: users and tickers, each being an array of values. How can I display these values in an Angular 5 HTML template similar to the screenshot above? I attempted to use ngFor but encountered errors. ...

Utilize ngModel to access input files in the array

Within my form, there is a file upload input: <input type="file" [(ngModel)]="item.image" name="image" #image> Can I retrieve #image.files[0] using the ngModel item.image directly (without creating a reference)? If not, what exactly does ngModel s ...

Swiping in Angular2 gets a new twist with Swiper typings

Having trouble importing typings for Swiper into my Angular 2 project. After installing Swiper and its typings using npm, I tried including Swiper in my component like this: import { Swiper } from 'swiper'; However, Atom displays an error: ...

Neglect certain concealed fields on AG Grid for now

Currently, I am working with Angular and AG-Grid to create a table below. By default, the table looks like this: However, when a user hovers over a row, two hidden buttons will appear as shown here: These buttons are actually associated with the two hid ...

Matching packages with mismatched @types in Webpack 2: A comprehensive guide

Having trouble implementing SoundJS (from the createJS framework) in my TypeScript project using webpack 2. In my vendors.ts file, I have the following import: import "soundjs"; Among other successful imports. The @types definitions installed via npm a ...

Custom component not rendering expected CSS style

I have successfully developed a custom web component without using any framework. I then proceeded to populate it with content from a template tag. Although I was able to manipulate the content using JavaScript, I encountered difficulties when trying to m ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

In JavaScript, constructors do not have access to variables

Currently, I am attempting to implement Twilio Access Token on Firebase Functions using TypeScript. export const generateTwilioToken = functions.https.onRequest((req, res) => { const twilioAccessToken = twilio.jwt.AccessToken; const envConfig = fun ...

Creating interfaces within props is essential for defining the structure of components

I'm trying to pass an Interface to one of my components, but I'm running into some issues with my approach. Here's what I have so far: import { InterfaceType } from "typescript"; type Props = { dataType: InterfaceType } export default ...

The absence of color gradations in the TypeScript definition of MUI5 createTheme is worth noting

Seeking to personalize my theme colors in MUI5 using TypeScript, I am utilizing the createTheme function. This function requires a palette entry in its argument object, which TypeScript specifies should be of type PaletteOptions: https://i.stack.imgur.com ...

What methods can be used to avoid getting distracted by input?

Is there a way to prevent the input field in angular-material2 from gaining focus when clicking on a visibility button? To see an example of how it works, visit: material.angular.io Image before pressing the button: https://i.stack.imgur.com/5SmKv.png ...

Utilizing Angular 4 alongside ng-sidebar to incorporate the class "right"

Just started using ng-sidebar in my Angular 4 project, but I'm a bit lost on where to place the "ng-sidebar--right" class. Could someone please guide me through this small issue (I'm new to this, so apologies in advance). Here's a snippet of ...

Encountering an issue where the module '@angular/compiler-cli/ngcc' cannot be located in Angular 8

Upon attempting to run ng serve from my terminal window, I encountered the following error: An unhandled exception occurred: Cannot find module '@angular/compiler-cli/ngcc' Here is an excerpt from my package.json file: { "name": "ProjectDeta ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

Is it possible to utilize a variable for binding, incorporate it in a condition, and then return the variable, all while

There are times when I bind a variable, use it to check a condition, and then return it based on the result. const val = getAttribute(svgEl, "fill"); if (val) { return convertColorToTgml(val); } const ancestorVal = svgAncestorValue(svgEl, "fill"); if (a ...

Angular - combining lowercase letters in an attribute

Hello, I'm new to using Angular and currently working on creating an attribute within a div tag. I have successfully achieved this task. However, I am in need of changing my input to lowercase during the concatenation. <!--"Fade" Slider--> < ...

Error Message: ES5 mandates the use of 'new' with Constructor Map

Below is the code snippet: export class ExtendedMap<T, U> extends Map { constructor() { super(); } toggle(key: T, value: U) { if (this.has(key)) { super.delete(key); ...

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...