The @Input parameter is populated during an HTTP call

Within my app.component.ts, I am invoking a function from a service that returns the result of an HTTP request:

questions: QuestionBase<any>[];
constructor(service: QuestionService) {
    this.questions = service.getQuestions().subscribe(val => console.log(val)); // gets logged after the other console log below
}

In the child component, the array named questions is further processed:

@Input() questions: QuestionBase<any>[] = [];
form: FormGroup;

constructor(private qcs: QuestionControlService) {}

ngOnInit() {
    console.log("onInit", this.questions); // called before questions is filled
    this.form = this.qcs.toFormGroup(this.questions);
}

The issue I am facing now is that the toFormGroup function within ngOnInit is getting called too early when the HTTP request hasn't completed yet. Given my lack of familiarity with Observables, I'm unsure how to ensure the function is only called after the HTTP request in getQuestions has finished. I have attempted using ngOnChanges, but it seems to trigger even before ngOnInit.

Answer №1

To start off, make sure to set the value for questions within the subscribe() function:

service.getQuestions().subscribe(val => this.questions=val);

Furthermore, in the child component, you can utilize ngOnChanges() and avoid binding the initial @Input() property when it is null. The SimpleChange class includes a boolean attribute firstChange.

  ngOnChanges(changes: {[key: string]: SimpleChange}) {
    if (!changes.questions.firstChange){
         this.form = this.qcs.toFormGroup(this.questions);}

  }

Answer №2

To ensure that the code executes correctly, it is important to verify if there are values present in the questions array before proceeding with any actions within the ngOnChanges lifecycle hook:

ngOnChanges() {
  if(questions && questions.length) {
     this.form = this.qcs.toFormGroup(this.questions);
  }
}

Answer №3

One approach is to invoke the toFormGroup method within the ngOnChanges lifecycle hook. Additionally, consider triggering the toFormGroup function only after the questions variable has been initialized with its first value. Unfortunately, I am currently using a mobile device and unable to supply a specific code snippet at this moment.

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 is the best way to invoke a function in a functional React component from a different functional React component?

I need to access the showDrawer method of one functional component in another, which acts as a wrapper. What are some best practices for achieving this? Any suggestions or insights would be appreciated! const TopSide = () => { const [visible, se ...

VueJs sub-component props not immediately reflecting changes

Currently, I have a setup where a parent component retrieves data from the server and then passes it down to child components through props. I want to use this data in a child component to instantiate a jQuery calendar. To ensure that the calendar setup i ...

Tips for managing Asynchronous Local Storage in Angular 2

I am currently working on setting the expiry for a token in local storage by utilizing the angular async local storage module. import { AsyncLocalStorage } from 'angular-async-local-storage'; const expiresAt = JSON.stringify((authResult.expires ...

Tips for combining Bootstrap 5's .is-invalid class with Angular's ng-invalid attribute

Bootstrap 5 provides a convenient way to indicate invalid input fields using the .is-invalid class. https://i.sstatic.net/UkgkU.png While working with a reactive form, I noticed that the "ng-invalid" style is applied when an input field is considered "in ...

Issue with Angular Elements: Zone.js has identified that ZoneAwarePromise has been detected

I've been experimenting with Angular Elements by creating two custom elements: a simple button and a basic input field. You can find them at these links: and Each element includes its own polyfills, main, runtime scripts, and styles bundled together ...

Adjusting the width of Ngb-datepicker in Angular 2

Can anyone help me with adjusting the widths of two Angular 2 ngb-datepicker components in my app? One is larger and the other is smaller, but I'm not sure how to differentiate between them and make them responsive. Thank you! ...

Upon the initial loading of GoJS and Angular Links, nodes are not bypassed

Hey there, I'm currently working on a workflow editor and renderer using Angular and GoJS. Everything seems to be in order, except for this one pesky bug that's bothering me. When the page first loads, the links don't avoid nodes properly. H ...

Angular 9 TestBed RouterTestingModule: Exploring the router.url Readonly Property

While transitioning from Angular 8 to Angular 10 in stages, I encountered an issue when upgrading to version 9. All of my TestBed.get(Router).url calls started throwing errors because the property had become read-only. For instance, the code TestBed.get(R ...

What is the best way to arrange items by utilizing the Array index in JavaScript?

Currently, I am attempting to make the elements within this angular component cascade upon loading. The goal is to have them appear in a specific layout as shown in the accompanying image. I'm seeking guidance on how to write a function in the TypeSc ...

Ensuring Angular Reactive Forms: Validation for Non-Empty Nested FormArray with Display of mat-error

I'm currently working on a project using Angular's reactive forms and facing a challenge with a nested structure. I need to validate that a FormArray of files within another FormArray is not empty. Each groupFiles can have multiple groups, and ea ...

The function of type 'PromiseConstructor' is not executable. Should 'new' be added? React TypeScript

.then causing issues in TypeScript. interface Props { type: string; user: object; setUserAuth: Promise<any>; } const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (type === "signup" ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

The "(click)" event doesn't fire upon clicking a material icon

After creating an <a> tag with a (click) event function call, I noticed that the click event works everywhere except for the arrows mat-icons within the code snippet below: <span *ngIf="section.pages.length>0"> <mat-icon *ngIf="secti ...

The Angular service is unable to access the Slim REST API endpoint

I have successfully configured a Slim REST API to retrieve data from the table trading_partner. <?php // Establish database connection require_once('dbconnect.php'); // Fetch all records $app->get('/path/to/trading_partner', fun ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Issue: Encounter StaticInjectorError while working with deployed Angular CLI project

We encountered an issue while attempting to deploy our Angular CLI (v.1.7.1) project on GitHub Pages and Firebase, resulting in the same outcome for both platforms. The ng serve command functions flawlessly on localhost:4200, and everything goes smoothly ...

Guide on setting default key/value state in TypeScript React application

Having the task of converting a React app to Typescript, I'm struggling to properly set the initial state of a hash object. Here is the original javascript code: export default class Wizard extends PureComponent { constructor(props) { su ...

Creating type definitions in TypeScript for an object received from an API with an unknown data type, and attempting to enforce specific types on it

Currently in the process of learning TypeScript, so please bear with me if I am not describing this accurately. I have a function that retrieves some data and returns a nested object. I then iterate over this object using forEach method. Although I have d ...

Discovering a method to recover information obtained through intercepting an observable

I am currently working on an Angular 6 cli application where a component utilizes a service to fetch data. As part of my project, I am incorporating an ngrx store into the application. I am considering abstracting the interactions with the store within the ...