Having trouble retrieving the value of a variable declared in a different function within an Angular project

I am encountering an issue when trying to retrieve the value of the existResults variable within a function that is called before the one where the variable is declared. The value returned is undefined.

  public existResults: any;

  ngOnInit(): void {
    this._activatedRoute.params.subscribe(params => {
      this.patientId = params['patient'];
      const testId = params['test'];
      this.getTestResults();
      this.getProccessesByTest(testId);
    });
  }

  getTestResults(id:any) {
    this._testsService.getTestResults(this.token, id, this.patientId).subscribe(
      response => {
        this.results = response.data;
        if (this.results.length == 0) {
          this.existResults = false;
        }else if(this.results.length > 0) {
          this.existResults = true;
        }
        console.log(this.existResults); //output true
      },
      error => {
        console.log(error);
      }
    );
  }

  getProccessesByTest() {
    console.log(this.existResults); //output undefined
  }

Answer №1

Give this a shot...

initializeComponent(): void {
this._activatedRoute.params.subscribe(parameters => {
    this.patientId = parameters['patient'];
    const testIdentifier = parameters['test'];
    this.retrieveTestOutcomes();
});
}

retrieveTestOutcomes(identifier: any) {
this._testsService.fetchTestOutcomes(this.token, identifier,
    this.patientId).subscribe(
        response => {
            this.outcomes = response.data;
            if (this.outcomes.length == 0) {
                this.noOutcomes = false;
            } else if (this.outcomes.length > 0) {
                this.noOutcomes = true;
            }

            this.fetchProcessesFromTest();
            console.log(this.noOutcomes); //result is true
        },
        error => {
            console.log(error);
        }
    );
    }

Answer №2

Make sure to integrate your getProccessesByTest() function within your getTestResults() function for seamless execution. Follow the code snippet below as a reference:

getTestResults(id:any) {
    this._testsService.getTestResults(this.token, id, this.patientId).subscribe(
      response => {
        this.results = response.data;
        if (this.results.length == 0) {
          this.existResults = false;
        } else if (this.results.length > 0) {
          this.existResults = true;
        }
        console.log(this.existResults); // Output will be true
        this.getProccessesByTest(testId);
      },
      error => {
        console.log(error);
      }
    );
  }

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

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

What is the best way to insert a placeholder React element into a different Component using TypeScript?

I've encountered a Typescript error that has me stumped. Check out the code snippet below: interface AppProps { Component: JSX.ElementClass; pageProps: JSX.ElementAttributesProperty; } const App = ({ Component, pageProps }: AppProps) => { co ...

Is it possible to alter the meaning of a word using the ngIf condition?

As a newcomer to Angular and Ionic, I am experimenting with retrieving JSON data from a URL and translating the words received to another language. My initial attempt using ngif did not yield the desired result! This is what I tried to do in order to chan ...

Having trouble with enzyme in React Typescript application

One of my components is called app.tsx import React, { useState } from "react"; const TestComponent = () => { return( <> <div className="head">hey there</div> <select name="xyz" id=&qu ...

reactjs: disable a specific eslint rule

I'm trying to figure out how to disable the "no-unused-vars" rule specifically for TypeScript interfaces. Here's a code snippet where I'm getting a warning: export type IKeoTableColumn<T> = { id: T; align: 'left' | ' ...

What steps should I take to address the issue of sanitizing a potentially harmful URL value that contains a

I've encountered a URL sanitization error in Angular and despite researching various solutions, I have been unable to implement any of them successfully in my specific case. Hence, I am reaching out for assistance. Below is the function causing the i ...

TypeScript - create an Interface that must have either the error field or the payload field, but

My Action type has the following requirements: MUST have a field type {String} CAN include a field payload {Object<string, any>} CAN include a field error {Error} Constraints: IF it contains the field payload THEN it cannot contain the field er ...

What steps should I take to generate a compiler error when a variable is not of the type "never"?

Imagine having a set of conditions with different possible values and wanting to cover each potential case. In the event of adding a new condition in the future but forgetting to handle it, it is important to have an error detection mechanism—ideally cat ...

The module './login/servcioprueba1.service' is missing the exported member 'prueba'. Kindly add this member to resolve the issue

I am working on an Angular 8 project that involves a service file. To generate the service, I used the command: ng g s servicioprueba1 After generating the service, I imported it into my code as shown below. Included in Block 2 is the line where I impor ...

Webpack bundling only a singular Typescript file rather than all of its dependencies

I'm currently facing a challenge while attempting to consolidate all the files in my Typescript project, along with their dependencies from node_modules, into a single file using Webpack. Despite trying multiple options, it seems that only the entry f ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Creating dynamic queries in Nodejs using MongoDB aggregation with both AND and OR conditions

I am facing an issue with MongoDB aggregation in my nodejs code. const query = { '$expr':{ '$and':[ {'$eq': ['$appId', req.user.appId]}, ] } } A filter object is coming from the frontend: { shops ...

Angular Placeholder Positioned at the Top

Hello, I am a beginner in Angular and need to create an input field that looks like this: https://i.sstatic.net/LUXfJ.png Everything is going fine except for the Vorname placeholder at the top. How can I place it there? Currently, I am utilizing Angular ...

Struggling with the transformation: Failed to find import "child_process" in TypeScript

I encountered an issue when trying to run my simple TypeScript project. I am receiving the following error: 'Error while transforming Could not resolve import "child_process".' You can see the error in this screenshot. This error occurs in my tsc ...

The Angular CLI release does not match the Angular version

After updating Angular to version 9, my previously smoothly running angular project started throwing this error: This peculiar error message popped up: This version of CLI is only compatible with Angular versions 0.0.0 || ^10.0.0-beta || >=10.0.0 <1 ...

Material UI Error TS1128: Expected declaration or statement for ButtonUnstyledProps

While working on my application that utilizes Material UI, I encountered an issue. I keep receiving a Typescript error and haven't been able to find a solution for it. TypeScript error in C:/.../node_modules/@mui/base/ButtonUnstyled/index.d.ts(3,1): D ...

Is there a way to make a peer dependency optional in a project?

In the process of developing module A, I have implemented a feature where users can choose to inject a Winston logger into my module. As a result, winston becomes a peer dependency. However, when attempting to include module A in another module without th ...

Angular HttpClient mapping causes the removal of getters from the target object

Utilizing the HttpClient to fetch Json data from an API, I am utilizing the autoMapping feature of the HttpClient to map the json response to a specified object in this manner: this.httpClient.post<Person>(url, body, { headers: headers, params: http ...

How Typescript Omit/Pick erases Symbols in a unique way

Recently, I have delved into TypeScript and started working on developing some custom utilities for my personal projects. However, I encountered an issue with type mapping involving Pick/Omit/Exclude and other typing operations where fields with symbol key ...

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...