Patience is key when waiting for one observable to respond before triggering another in Angular's async environment

What is my goal?

  • I have several components with similar checks and data manipulation tasks. I am looking to centralize these tasks within an observable.
  • To achieve this, I created an observable named "getData" in my service...
  • The complexity lies in the fact that "getData" includes an if check -> if there is data in the local storage, return it. if not, make an API call (getbyid) to fetch the data, manipulate it, and then return it.

NOTE: The getbyid() function cannot be altered, and both functions reside in 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.asObservable()
         })
      console.log('after api');
        
    }else{
      data.next({data:payload})
      return data.asObservable()
    }

    }
     
  }

CURRENT scenario: the code is currently calling getbyid but proceeding without waiting for the response. This could be resolved by ensuring that the code waits for the response before proceeding further.

Answer №1

In this situation, you can achieve the desired outcome without using a BehaviorSubject. Here is an example of how you can accomplish this (assuming "payload" represents the content stored in 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 the variable payload has a value, we return an observable containing it. Otherwise, we return an observable with a backend call.

In both scenarios, you will need to subscribe to the method getData and wait for the response wherever it is called.

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

Issues occur during installation of Angular on Mac Catalina, encountering errors while trying to run the installation command for Angular: `% sudo npm

My npm version is 6.14.6 and node version is v12.18.3. I have attempted the following: Added sudo in the beginning, but still not working. Tried to install har-validator using command: sudo npm install har-validator Attempted: npm install --force expo-cli ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...

AG-Grid hierarchical data structure

Transitioning from kendo tree list to ag grid tree data grid, I am facing a challenge. My table data is currently formatted as shown below, but ag grid requires data in the form of a string array of nodes in a tree. How can I adapt or customize my existing ...

What is the best way to prevent URL modification in Angular?

Currently, I am working on a project with a specific page (let's call it localhost:XXXX/notification-page) and we want this to be the only URL that can be accessed. Any attempt to change the URL should redirect users back to the notification-page. As ...

Create a variety of URL formats for various object cases

Can you guide me on how to verify and create a URL under different circumstances? I am dealing with 3 cases that involve different types of objects: "repositories": { "toto": { "tata": "https://google.com/", ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

Animation on React child component disappears when re-rendered

My React application utilizes Material UI with a component (let's call it DateSelector) as shown below, slightly altered for demonstration purposes. https://i.sstatic.net/RlPZa.gif Material UI provides animations for clicks and interactions within i ...

Is it possible to utilize the returned value of a function within an if statement?

Is there a way to return the result of a function without needing to declare a variable? Can you return the result of a function in a single line? How can you return the result of a function inside an if statement? Is it possible to use a function's ...

Having trouble with Apple Login functionality in Safari on my Angular application

While implementing apple login in my web app, I encountered an issue with Safari browser. Instead of opening the redirect URI in a new tab, it displays a finger touch enabled login popup. This prevents the passing of the redirect URI and causes problems wi ...

Error message in VueJS TypeScript: Implicit declaration of type 'props' as 'any'

Currently, I am working with vue 2.6 and typescript 3.8.3. The issue arises when I attempt to apply a validator to a prop. I am encountering error message TS7006: Parameter 'props' implicitly has an 'any' type. Below is the ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

There is no index signature containing a parameter of type 'string' within the type '{ appointments: { label: string; id: number; minWidth: number; }[]; }'

Just getting started with React and Typescript. I'm attempting to extract data from the configuration file based on the input(props), but it seems like Typescript is throwing errors. Any suggestions on how to tackle this issue? config.json { "t ...

How can one avoid the use of an opening curly bracket in Angular?

Is there a way to avoid the first opening curly brace shown below? <div> { <ng-container *ngFor="let x of [1,2,3,4]; let last=last"> {{x}} <ng-container *ngIf="!last">,</ng-conta ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

Mapping a TypeScript tuple into a new tuple by leveraging Array.map

I attempted to transform a TypeScript tuple into another tuple using Array.map in the following manner: const tuple1: [number, number, number] = [1, 2, 3]; const tuple2: [number, number, number] = tuple1.map(x => x * 2); console.log(tuple2); TypeScript ...

Struggling with my initial Angular 2 project, having trouble showcasing data from an object. Any assistance would be greatly

As a newcomer to Angular 2, I am currently in the learning phase and utilizing tutorials and documentation from the official website. Below is the code snippet that I have been working on: import { Component } from '@angular/core'; export class ...