Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {Router, ActivatedRoute, Params} from '@angular/router';

import { Country } from './../../model/country';
import { CountryService } from './../../service/country.service';

@Component({
  selector: 'app-country-add',
  templateUrl: './country-add.component.html', 
  providers: [CountryService]
})
export class CountryAddComponent implements OnInit {
  
   private country: Country;
   private countryId: number;
   private countryForm: FormGroup; 
    
  constructor(private _countryService: CountryService,private formBuilder: FormBuilder, private activatedRoute: ActivatedRoute ) {
    this.activatedRoute.queryParams.subscribe((params: Params) => {
        this.countryId = params['id'];        
      });
       if(this.countryId!=null){
      this.getCountry(this.countryId); 
       console.log('konstruktor');
     }       
  }

  ngOnInit() {   
    console.log('on init');
    this.createForm();      
    this.setForm();      

  }

  private createForm(): void {
    this.countryForm = this.formBuilder.group({     
          name: ['', Validators.required],     
        });
  }

  private setForm(){   
    this.countryForm.setValue({
      name: this.country.name     
    })
     
  }

   createCountry({value, valid}){
    this.country = Country.fromJSON(value);    
    this._countryService.createCountry(this.country).subscribe(null,error => alert(error));
  } 

   getCountry(id: number){
     this.country = new Country();    
    this._countryService.getCountry(id).subscribe(data=>{     
      this.country.name = data.name;
      this.country.id = data.id;
       console.log('getCountry method')
    }  
    , error => alert(error));
    
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

I'm facing an issue related to the method execution order in my Angular 2 component. I expected the order to be constructor -> onInit -> getCountry, but it seems to be constructor -> getCountry called in constructor -> ngOnInit when loading the template of this component. The console log order can be seen here: enter image description here

Can anyone provide an explanation for this behavior?

Answer №1

It appears that the order of execution is (constructor => getCountry => ngOnInit). The reason you see 'getCountry method' logged in the console is because it is being executed asynchronously within the response of your service.

I noticed that you are using the country's name in your setForm() function. My suggestion would be to call createForm() within the constructor and then invoke setForm() inside the callback from the getCountry() service.

Updated code snippets can go here...

You may also consider implementing async/await if your services return Promises for smoother handling of asynchronous operations.

Another option could be to handle asynchronous operations with async/await:

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

Is the order of execution of extraReducers before or after the reducers?

I was curious about the createSlice function in redux-toolkit and how it handles the order of execution for extraReducers compared to reducers. Can we determine if the extraReducers are executed before or after the reducers, or is the order indeterminate? ...

Capturing AJAX responses within a Chrome Extension

We are currently in the process of developing a Chrome extension to enhance an existing system by simplifying various tasks. This extension will heavily utilize AJAX technology, making it more efficient compared to web scraping or manually triggering even ...

Vue 3 throws an error stating: "An uncaught DOMException occurred because the string contains an invalid character."

Exploring the capabilities of vue.js on a basic website. The setup consists of a single index.html file and all JavaScript is housed in an index.js file. The website is a work in progress, but there are no blockers preventing the JavaScript functionality ...

What is the most efficient method for identifying and modifying an element's in-line style while performing a swipe gesture?

Recently, I've been developing a left swipe gesture handler for chat bubbles. Implementing touchMove and touchStart seems like the logical next step, but for now, I'm focusing on making it work seamlessly for PC/web users. I managed to make it f ...

Showing a gallery of images in React

I have a unique situation where I am working on setting a variable to match the import statement that calls for images. Once I have this variable assigned, I want to use it to display the corresponding image. For instance, if my code generates the name &ap ...

Navigate audio tracks with JavaScript

I'm currently facing an issue with using a button to switch between two audio tracks being played in the browser. The method I have implemented switches to the second track, but it doesn't change the audio that is played afterward - instead, it s ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

Having trouble adding custom props to MUI-Material ListItemButtonProps? Facing a TypeScript error?

This particular task should be relatively straightforward. I am seeking a custom component that inherits all props from ListItemButtonProps, while also adding an extra state prop: type SidebarListItemButtonProps = ListItemButtonProps & { state: Sideb ...

Leverage the power of express-session in your NextJS project

Currently, I am working on developing a login system using NextJS and MySQL. I am looking to implement sessions for user login, but I am unsure of how to integrate express-session with NextJS. Can anyone provide guidance on whether express-session can be ...

Angular2: Implement a feature to append textbox input to a span element upon button click

I'm completely new to Angular2 and I could really use some assistance with the following task. I need to take the input from a textbox and add it to a span in HTML. The requirement is to only make changes in the .ts file. I'm having trouble figu ...

Do you need to define a schema before querying data with Mongoose?

Is it necessary to adhere to a model with a schema before running any query? And how can one query a database collection without the schema, when referred by the collection name? This scenario is demonstrated in an example query from the Mongoose document ...

The audio must start playing prior to being forwarded to a new page

As I delve into the world of website development on my own, I have encountered an interesting challenge. At the top of my webpage, I have embedded an audio file within a button. If the user chooses to mute the audio, the navigation links will remain silent ...

When using the Ng --version command on a development package, it throws an error

I encounter an error with a development package when cloning a repository. I would greatly appreciate any advice on how to resolve this issue. https://i.stack.imgur.com/DBp5r.png ...

Dilemma: Navigating the Conflict Between Context API and Next.js Routing in React

Recently, I was following a Material UI tutorial on Udemy and decided to set up a Context API in Create React App without passing down props as shown in the tutorial. Later on, when I tried migrating to Next JS with the same Context API, I started encounte ...

The Angular 7 template falls short of occupying the entire page

I am currently working on converting an HTML page into my Angular project. While it functions correctly in the HTML version, it does not fill up the entire page when transferred to Angular. You can view an example of this issue on StackBlitz at the followi ...

Retrieve the most recent ajax request and cancel any other ones

I've been exploring this issue and it seems fairly straightforward, but I'm having trouble finding a solution. I have several requests that call different URLs. However, for each URL, I only want to receive the last result from the same URL being ...

The powerful combination of Nuxt, Vuex, and Computed Properties allows for

Currently exploring Nuxt.js with Vuex, I have created a basic form containing an email field, a password field, and a button. All my state, mutations, and actions are functioning correctly. However, I encountered an issue when trying to create a computed ...

Is there a way to program a function that can automatically trigger or refresh an HTTP POST method?

How can I create a method in a distant component that will run a POST request when a button is clicked? I believe I need to use a service in this situation. It's not necessary for it(this.qwe) to be in the constructor, it's just an example... ...

What circumstances could lead to a timeout while executing sequelize in a Node.js environment?

Within my application built with Node.js version 10.15.0, I utilize the sequelize package (version 4.44.3) to establish a connection to a remote MySQL database. This application operates within a Docker container. However, after prolonged usage, I encounte ...

The data from the Flickr API is consistently unchanging

I created a simple weather app that retrieves weather data using a "POST" request and displays it successfully. Users have the ability to search for weather by city, and I wanted to enhance the app by loading an image of that city through a separate jQuer ...