When using the subscribe method in Angular4, I am encountering a null value for the data

After receiving data from my subscription and displaying it, I encounter an issue when calling my function as it returns a "null" value. I apologize for any language errors in my message. Thank you.

 this.service.prepareNewVersion().subscribe(data2 => {
       console.log("data2 ", data2);
       this.service.myBlockPeriod = data2;
       console.log(" prepareNewVersion ",   this.service.myBlockPeriod);
  });
 console.log(" before ",   this.service.myBlockPeriod);
 this.showYearsExec();


private showYearsExec() {
        console.log("showYearsExec", this.service.myBlockPeriod);
        let list: Array<string> = this.service.myBlockPeriod;

    if (list !== null) {

        list.forEach(element => {
            this.arrayYears.push(element.substring(0, 4));
        });



        // Remove duplicate years.
        let unique = this.arrayYears.filter(function (elem, index, self) {
            return index === self.indexOf(elem);
        })

        // Populate year combo in the view.
        this.arrayYears = unique;

        // Add to service
        this.service.yearsInExec = unique;
    }

}

https://i.sstatic.net/8DVPV.png

Answer №1

When your code is executed asynchronously, the "this.showYearsExec()" method is called before the promise from the "prepareNewVersion()" method is resolved, resulting in a null value.

To fix this issue, make sure to call "this.showYearsExec();" within the subscribe method as shown below:

this.service.prepareNewVersion().subscribe(data2 => {
       console.log("data2 ", data2);
       this.service.myBlockPeriod = data2;
       console.log(" prepareNewVersion ",   this.service.myBlockPeriod);
       console.log(" before ",   this.service.myBlockPeriod);
       this.showYearsExec();
  });

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

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

Enhancing current interfaces

I'm exploring Koa and the module system in Node.js. Although I'm not asking about a specific koa question, all the code I'm working with involves using koa. In Koa, every request is defined by the Request interface: declare module "koa" { ...

Using ngModel to bind input fields with predefined default values

I have an input field and I'm trying to set default values, but when using ngModel the input fields are coming up empty. How can I set default values that the user can change? <div class="control"> <input #name="ngModel" ...

Simulated FTP Connection Setup and Error Event in Node.js using Typescript

In my Node-Typescript-Express application, I am utilizing the FTP library to connect and retrieve files from a designated location. As part of creating unit tests, I am focusing on mocking the library to ensure coverage for code handling Ready and Error ev ...

Call a function within a stateless component in a React application

I have a question regarding my React component. I am attempting to call the function ButtonAppBar within my stateless component, but the TypeScript compiler is throwing an error stating '{' expected. I'm unsure whether I need to pass it to m ...

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice I am developing an angular application that fetches data from an API and presents it on the page The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls apiservice.service.ts ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

Angular Iterate Array Forms

Is there a way to iterate my rows based on user input? For example, if the user enters 2 values, I need to display 2 rows. How can I achieve this using FormArray? setCount(count:any){ console.log(count); this.count = count; this.countArray = Ar ...

Nuxt encountered an issue with Vue hydration: "Tried to hydrate existing markup, but the container is empty. Resorting to full mount instead."

I'm facing an issue while trying to integrate SSR into my project. I keep encountering this error/warning. How can I pinpoint the problem in my code? There are numerous components in my project, so I'm unsure if I should share all of my code, b ...

Issue with the onClick event in next.js and TypeScript

While working on the frontend development of an app, I encountered a strange issue with the onClick function. The error message I'm seeing is: Type '(e: SyntheticEvent<Element, Event>) => void' is not assignable to type 'Custom ...

Subscribing to a GraphQL mutation through Angular with the Appsync client

Currently, I am developing a chat application in Angular using GraphQL with Appsync on AWS. The current process for creating a new chat involves mocking up the chat and sending it to the server. On the server-side, a unique chat_id is generated for each ch ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Enhance your angular application with universal support using the CLI for Angular 6

After creating a new Angular6 application using Angular CLI, I used the following command: ng generate universal This added support for Universal rendering. Everything is working fine, but I noticed that it also added the following code to my angular.jso ...

Issue: The formGroup function requires a valid FormGroup instance to be passed in. Data retrieval unsuccessful

My goal is to retrieve user data from a user method service in order to enable users to update their personal information, but I'm encountering an error. Currently, I can only access the "prenom" field, even though all the data is available as seen in ...

Issue encountered during the creation process of a new component within Angular 4

While attempting to create a new component named signup-form using the command: ng generate component signup-form / ng g component signup-form An error is being thrown that reads: Unexpected token / in JSON at position 1154 The source of this error i ...

Rollup bundling with Typescript and troublesome rollup-plugin-typescript2 experience

I'm currently facing some unexpected challenges while attempting to extract a small portion of a monorepo into a web client library. The issue seems to be related to the configuration of Rollup, as shown below: import resolve from "rollup-plugin-node ...