Unable to retrieve any data from BehaviorSubject within the observable

Trying to pass data inside an observable function from multiple services to an unrelated component without using service calls by utilizing BehaviorSubject has yielded mixed results.

service.ts

export class Data{
 name:string;
 age:number;
 class:string;
 constructor(){
  this.name = "";
  this.age = null;
  this.class="";
 }
}
@Injectable()
export class InfoService {

 public myData = new Data();
 dataSubject = new BehaviorSubject<any>(this.myData);
 dataInfo = this.dataSubject.asObservable();

 constructor(private http:HttpClient){}
 getData(id:Id):Observable<any>{
  this.http.get(url+"id="+id).pipe(first()).subscribe(res=>{
    this.myData = res['data'];
    this.dataSubject.next(this.myData);
    console.log(this.myData);
  }
  return this.http.get(url+"id="+id);
}

The value from the console.log in the service file was obtained successfully.

componenet.ts

export class Employee implements OnInit{

    constructor(public infoS:InfoService ){}

    ngOnInIt(){
        this.infoS.dataInfo.subscribe(res=>{
          console.log(res);
        }
    }
}

In the component file, the console.log gives an empty Data object. Upon inspecting the console, it was noticed that the component line runs before the service line. Is there a way to ensure the component runs after the service? Furthermore, some instances are working correctly. The console indicates that in the successful cases, the component line executes both before and after the service line. Therefore, for those that work, the component line actually runs twice - once before the service line and once after, leading to success.

Answer №1

dataInfo will capture the initial value of a behavior subject and remain static thereafter. To receive updates whenever the behavior subject changes, it is necessary to directly subscribe to dataSubject:

ngOnInIt(){
   this.infoS.dataSubject.subscribe(res=>{
          console.log(res);
   }
}

Answer №2

Below are some steps you can take:


this.dataService.retrieveData.subscribe(info=>{
   if(info) {
       console.log(info);
   }
}

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

Is there a way to show a mat-icon in a disabled state?

In my Angular project, I am working on implementing a mat-accordion component that consists of multiple panels. These panels can either be enabled or disabled, and I am using material-ui icons to visually represent their status. For an enabled panel, the c ...

Fixing Error 415 when Sending Angular Posts to Asp.Net Web Api on IIS

I'm having a difficult time figuring out how to make a simple Web Api call work, and I'm feeling quite frustrated because it's much more complicated than anticipated. I have created a basic Web Api (for testing purposes) that is being consu ...

What is the best way to toggle a bootstrap 4 modal using an Angular2 component and Typescript?

I am struggling to toggle a Bootstrap modal using Typescript with the default bootstrap 4 Modal. Below is the code snippet: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> &l ...

How to instantiate an object in Angular 4 without any parameters

Currently, I am still getting the hang of Angular 4 Framework. I encountered a problem in creating an object within a component and initializing it as a new instance of a class. Despite importing the class into the component.ts file, I keep receiving an er ...

Error: Uncaught TypeError in AuthContext in Next.js 13.0.6 when using TypeScript and Firebase integration

I'm currently trying to display a page only if the user is present in my app. Right now, the app is pretty bare bones with just an AuthContext and this one page. I had it working in React, but ran into some issues when I switched it over to TS and Nex ...

Facing issues while trying to update Angular from version 12 to 13 due to conflicting peer dependencies

I'm in the process of upgrading an Angular project from version 12 to 13, following the guidelines provided on the Angular update website https://update.angular.io/?v=12.0-13.0. Before starting the upgrade procedure, this is how the package.json file ...

unable to select date on mat-calendar

I'm trying to add special dates to a mat-calendar by highlighting them. Here's the code I have so far: app.component.ts: datesToHighlight = ["2019-06-22T18:30:00.000Z", "2019-06-06T18:30:00.000Z", "2019-06-24T18:30:00.000 ...

Exploring TypeScript Heartbeat functionality with Nodejs ws module

I am currently in the process of setting up a WebSocket server using NodeJs and TypeScript. The WebSocket server implementation I have chosen is from the ws package, supplemented by the @types/ws package for typings. My goal is to have the server send out ...

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

Prisma : what is the best way to retrieve all elements that correspond to a list of IDs?

I'm currently implementing Prisma with NextJs. Within my API, I am sending a list of numbers that represent the ID's of objects in the database. For example, if I receive the list [1, 2, 12], I want to retrieve the objects where the ID is eithe ...

Increase the width of columns when hiding additional columns

I have the following HTML and CSS code. If one of the columns is hidden, I would like the other 3 columns to expand. I don't believe using col-md-3 will work in this situation. Is there a way to achieve this? <link href="https://stackpath.boots ...

Optimizing the Angular app for production can lead to the malfunction of specific components

I am currently working on an Angular application and encountering some issues during the compilation process using ng build. When I compile the project for production deployment with the optimization option enabled, I am faced with console errors that prev ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

Retrieve the object property based on an array of indices

I am looking to create a function that can retrieve a specific property of an object based on an array of property names const getObjectProperty = (arr: string[], object: any) { // This function should return the desired object property } Expected Outco ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Creating Multiple Result Lists in MUI Autocomplete Based on Option Properties: A Step-by-Step Guide

I have a query about displaying results using the MUI Autocomplete component. I am looking to categorize the results into two separate lists placed side by side. Currently, I have a working searchbar with one list of results. However, I aim to segregate t ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Strategies for launching a website with NPM-managed JavaScript dependencies?

Currently, in the process of building a website with Angular2 and TypeScript, I adhered to the 'Getting started' guide from the official website. However, upon completion, I noticed that my node_modules directory is approximately 70MB in size. Th ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...