Issue with Angular: Global variable not updating within Subscription function

I'm encountering difficulties with updating a global variable in Angular 7 by using TypeScript.

I am utilizing a service that retrieves JSON data from a database via a Restful API

The service :

export class myService {
  constructor(private client : HttpClient) { }

  dossierSubject = new Subject();
  private dossiers : any[];

  getExtract(){
    this.client.get<any[]>('http://localhost:9090/dossiers')
    .subscribe(
      (response) => {
        console.log("Data acquisition in progress");
        this.dossiers = response;
        this.emitDossierSubject();
        console.log('Received data ' + response);
      },
      (error) => {
        console.log('Error ! : ' + JSON.stringify(error));
      }
    );
  }

   emitDossierSubject(){
    this.dossierSubject.next(this.dossiers.slice());
  }

MyService is functioning properly and I am able to retrieve the desired data, then I call the service in the component

The component

 export class tabComponent implements OnInit {

  constructor(private dossierService : myService) { }

  private dossierSubscription : Subscription;
  private listeDossiers : any[];

  ngOnInit() {
    this.spinnerStatus = true;
    this.dossierService.getExtract();
    this.dossierSubscription = this.dossierService.dossierSubject.subscribe(
      (dossiers : any[]) => {
        this.listeDossiers = dossiers;
        console.log(listeDossiers); //dossiers [object][object]
        this.spinnerStatus = false;
      }
    );
    console.log('Received data : '+ this.listeDossiers);  //undefined
  }

I would appreciate insights on why my global variable "listeDossiers" is only updated within the subscribe function.

I attempted using a subject for the "listeDossier" and refreshing it right after changing the variable within the subscription, but without success.

Thank you for your assistance.

Answer №1

It seems that changing console.log(listeDossiers); to console.log(this.listeDossiers); might solve the issue.

Additionally, the console.log statement outside the subscribe block may execute before the http request is completed. Trying to print it within the ngOnInit() function without properly waiting for the assignment within the subscribe may cause unexpected results.

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

The type 'ElementTypes' cannot be assigned to type 'ElementTypes.word'

After recently learning TypeScript, I encountered an error that made me think I need to write a narrower type for it or something along those lines. Here is the code snippet in question: enum ElementTypes { h1 = 'H1', word = "WORD" ...

Could Angular be automatically applying margins or padding to my component?

I'm encountering a minor issue.. I'm attempting to create a "Matrix" to construct a snake game in angular, but there seems to be an unremovable margin/padding. Below is my code: <!-- snake.component.html --> <div id="ng-snake-main&q ...

Retrieve functions contained within the component.ts file of an Angular library: tips and tricks

I have developed an Angular library, named 'mylib', where I have utilized only the mylib.component.ts file. The HTML element codes are included inside the template variable of this file, along with the functions responsible for modifying these el ...

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

Retrieve component information from the service

Incorporated within my component is a form that I'm utilizing with reactive form and my intention is to reach this form through my service. For example: const id = MyComponent.id and inside my component: @Output: public id: number = 7; ...

Exploring the Behavior of Typescript Modules

When working with the module foo, calling bar.factoryMethod('Blue') will result in an instance of WidgetBlue. module foo { export class bar { factoryMethod(classname: string): WidgetBase { return new foo["Widget" + classname](); ...

how can I display the JSON description based on the corresponding ID using Ionic 3

I have a JSON file containing: [{ "id": "1", "title": "Abba Father (1)", "description": "Abba Abba Father." }, { "id": "2", "title": "Abba Father, Let me be (2)", "description": "Abba Father, Let me be (2) we are the clay." }, { ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Discovering the IMEI number with Ionic4 and Angular

Recently, I started working with the Ionic framework and I'm trying to find a way to uniquely identify each device. My initial thought was to obtain the IMEI number, but I'm unsure of how to do that. I attempted to use Ionic4 with Angular cordova ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

Encountering a 404 Error in Angular 17 When Refreshing the Page

After completing my Angular 17 project and deploying it to hosting, I encountered an issue where pressing F5 on the page would redirect me to a 404 error page. Despite searching for solutions, I was unable to resolve this situation within Angular 17. I am ...

Having trouble resolving all parameters for the component xyz: (?, ?) after the upgrade to Angular 2 CLI

After upgrading my Angular2 project from Beta .21 to beta .25.5, which was functioning smoothly, I resolved all errors for both AOT and non-AOT (e.g. ng serve) functionalities. However, upon browser loading, I encountered an error affecting multiple servi ...

Empty dialog box displayed in production for Angular material datepicker

I'm facing an issue that I can't seem to figure out. The code works perfectly fine when I run it locally using ng build and ng serve. However, when I moved it to production, it started misbehaving. When I tried to replicate the issue in my local ...

Modifying data within tables using Angular 4

I am currently working on a task to manage the employee table in Angular by enabling functionalities to display, add, delete, and update the table. Below is an image of the table: https://i.sstatic.net/p8qwZ.png At the moment, all fields in the table are ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

An issue has arisen where Selenium Auth0 is unable to establish a connection with the server

I am using a protractor selenium test for an angular2 application that I execute with the command protractor conf.js --params.login.username=John --params.login.password=Doe. The purpose of the test is to attempt to log in to the backend and intentionally ...

TSLint now requires promises to be handled correctly using the `finally` clause

Encountering an error from TSLint, I am working to comprehend why it is raising concerns. In my code, there is a function that calls another method which returns a promise. However, the initial function does not return the promise; instead, it waits for c ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

The React-Typescript error message is stating that the module "react-router-dom" does not have the exported member "RouteComponentProps"

I encountered an issue with my project involving a login page and the usage of "RouteComponentProps". Unfortunately, I received the following error: Module '"react-router-dom"' has no exported member 'RouteComponentProps'. Upon attempt ...

Develop a cutting-edge Drag and Drop Functionality using the innovative Material CDK

Here is a unique link you can check out: https://stackblitz.com/angular/nabbkobrxrn?file=src/app/cdk-drag-drop-enter-predicate-example.ts. In this example, I have specific goals: I want to be able to select only one number from the "Available numbers" l ...