Encountering unexpected null values post-service invocation in Angular 2

I have encountered an issue in Angular 2 where a variable is returning undefined. The problem arises when a function calls a service to initialize a variable, which is then used in another function to make a get HTTP request. However, the get request fails because the variable is undefined.

Here is the code snippet:

variable:any;
constructor(private http: Http, private serviceOne: ServiceOne){
function1();    //service call to get data
function2();    //http get request
}

function1(){
calls request  //subscribes data
data =>{this.variable = data.var};
}

function2(){
console.log(this.variable);   //undefined
http get request uses this.variable
}

Answer №1

It appears that function1() in your code makes an asynchronous call to set data to a variable. In such a scenario, you must ensure that you wait for the async operation to finish before proceeding to function2().

Consider the following approach:

variable:any;
constructor(private http: Http, private serviceOne: ServiceOne){
function1();    //initiate service call to fetch data
}

function1(){
yourAsyncCall().subscribe(res=>{
this.function2(res);
}) 
}

function2(variable){
this.variable = variable;
//Utilize the variable in your http request
}

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

When invoking a function within another function, it is essential to ensure that both values are returned within the function

When calling a function within another function function1(){ return this.a } function2(){ return this.b } To output in string format, you can call function1 inside function2 function2(){ var resultOfFunction1 = this.function1(); return resultOfFunction1 ...

What is the most effective method of testing with jest to verify that a TypeScript Enum list contains all the expected string values?

Recently, I created a list of enums: export enum Hobbies { Paint = 'PAINT', Run = 'RUN', Bike = 'BIKE', Dance = 'DANCE' } My goal is to iterate through this list using Jest and verify that all the string ...

Accelerated repository uses TypeScript to compile a node application with dependencies managed within a shared workspace

Struggling to set up an express api within a pnpm turborepo workspace. The api relies on @my/shared as a dependency, which is a local workspace package. I have been facing challenges in getting the build process right. It seems like I need to build the s ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Using ng-src and ngFor in Angular applications

Imagine taking photos based on an ID and storing them in an array like this: data.attributes.photos = [ "12.jpg", "12_1.jpg", "12_2.jpg" , 12_3.jpg, ... ] Then, using ngFor to display them: <ngb-carousel> <ng-template ngbSlide *ngFor="l ...

Angular project seems to be stuck in a continuous cycle of

Currently, my application consists of spring boot as the backend and Angular as the front end. However, when I try to access the application through localhost:4200, the page continuously refreshes every few seconds. This issue did not occur previously, so ...

What is preventing me from connecting to dockerized npm from my host machine?

Issue - A server running inside a docker container is not responding when accessed from outside the container on an OSX host. web: image: my_web build: context: ./ dockerfile: web.docker container_name: my_web networks: ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

Nested function TypeScript declarations

Currently, I am attempting to define a type for my controller function in (nodejs) similar to the following export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) { res.status(200).json({ success: true}); }) ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

Tips for determining the datatype of a callback parameter based on the specified event name

Let's say we have the following code snippet: type eventType = "ready" | "buzz"; type eventTypeReadyInput = {appIsReady: string}; interface mysdk { on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void } mysdk.on("ready", ...

Encountering a TypeScript error when using Redux dispatch action, specifically stating `Property does not exist on type`

In my code, there is a redux-thunk action implemented as follows: import { Action } from "redux"; import { ThunkAction as ReduxThunkAction } from "redux-thunk"; import { IState } from "./store"; type TThunkAction = ReduxThunk ...

Using the $http.post function in AngularJS to pass an array of objects is not successful

I need to send an array of objects from my main merchandise.php file to another PHP file called process_cart.php using the AngularJS $http.post method. I plan to use a foreach loop in the receiving file to display the contents of the cart. Below is how my ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...

How to dynamically load a component in Angular 2 using a string argument

I am currently developing an app that performs static analysis on components from an Angular application and then renders them within another Angular app. This app serves as a comprehensive style guide with detailed information on inputs and other key aspe ...

What is the best way to trigger a function on the fly within my loop?

As a newcomer to Ionic and hybrid app development, I'm struggling with how to phrase my question. Essentially, I need help with opening an ion-select field by clicking on another button in my app. Although the functionality somewhat works, it doesn&a ...

Best approach for managing Union Types in Angular 16 Templates / Utilizing Type Inference?

Currently, I'm immersed in a project using Angular 16 where my focus lies on applying a reactive declarative method. Oftentimes, I find myself working with Observables that emit varying data types - either successful data or an error object. Each ret ...

Deliver the object to the styled component in Material UI

I have a styled component: import {styled} from '@mui/material/styles'; export const MovieModalStyle = styled(Box)(({theme}) => ({ // ... background: `url(${'https://image.tmdb.org/t/p/w780/' + movie.backdrop_path})`, })); Look ...

Unable to employ the inequality operator while querying a collection in AngularFire

I'm facing a challenge with pulling a collection from Firebase that is not linked to the user. While I've managed to query the user's collection successfully, I am struggling to retrieve the collection that does not belong to the user using ...

You must include the formControlName within a parent formGroup directive

Upon creating a model-driven form, an error is encountered: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ...