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 there a way to make a React Component to update and navigate to a specific position using react-sound

Currently, I am in the process of constructing an audio player utilizing react-sound. One feature I aim to incorporate is the ability to return to a specific position within the audio track. At the moment, this is my approach: goToVeryCustomPosition() { ...

Is there a way to trigger the vue-cli build command automatically when specific files are modified?

One way I can build my JavaScript file is by using the following command: vue build main.js --dist dist --prod --lib While this works, I am looking for a way to automate this process whenever I make changes to my JS or Vue files. I prefer not to rely on ...

Discover the process for finding a Youtube Channel Name with querySelectorAll

OUTPUT : Console URL : https://www.youtube.com/feed/trending?gl=IN document.querySelectorAll('a[class="yt-simple-endpoint style-scope yt-formatted-string"]')[0].innerText; document.querySelectorAll('a[class="yt-simple-endpoi ...

Tips for running code extracted from a JSON payload

I have a JSON string that contains HTML and JavaScript code. I want to display this code on a page in my React app, but instead of just showing it as a string, I want the HTML and JavaScript to be executed as if it were hard coded. Currently, the code is ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Discovering the file extension and ensuring its validity when imported from Google Drive

I am facing an issue with a select tag that has 3 options: powerpoint, pdf, and spreadsheet. When uploading from Google Drive, there is no validation in place, so I can give a ppt link to the pdf option and it will still upload. Can someone help me with va ...

Building a custom HTML and JavaScript player to showcase multiple videos on a webpage

UPDATE: The solution has been discovered, shared, and marked as the top answer below. In the process of creating my portfolio website using HTML, CSS, and JS, I encountered a challenge regarding the addition of multiple videos on various pages. While fol ...

Discover the key to optimizing your JavaScript development workflow by automating project structures and eliminating the need to start from scratch

I was looking for a way to streamline the process of setting up project structures for my projects so that I could utilize ALE linting and fixing without any hassle. After trying out one method, I'm confident that there must be a more efficient soluti ...

Steps to activate a single button within a deactivated fieldset

Is there a way to deactivate all elements within a Fieldset, while keeping certain buttons active? Check out this demo. <fieldset ng-disabled="true"> <legend>Personalia:</legend> Name: <input type="text"><br> Em ...

"Reposition all elements contained within a div that have a specific class

I'm completely new to Javascript and I've been trying to move all elements with a specific class inside a particular div. After doing some research, I found a solution that worked using IDs. However, when I tried to adapt it to work with classNam ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

Why do my paths encounter issues when I alter the manner in which I deliver my index.html file?

I recently made a decision to change the method of serving my index.html file from app.use('/', express.static(__dirname + '/..')); to app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/../index.htm ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Implementing Angular 2 - Steps to ensure a service is accessible within the app module

I'm running into an issue trying to utilize a function within a service that I believed was globally accessible. The service in question is named SavedNotificationService: import { Injectable } from '@angular/core'; @Injectable() export cl ...

Utilizing TypeScript: Importing a typed module within a d.ts file (from an npm package)

I am currently working on integrating a definition file into an npm package that has dependencies on React. The specific library in question can be found at https://github.com/eiriklv/react-masonry-component. In my TypeScript project, I have successfully ...

When a page with parameters is reloaded, React fails to initiate

I'm encountering an issue with my application in development mode on localhost. When I try to reload the app on a route with parameters, for example: localhost:8080/item/2 React fails to initialize and only a blank page is displayed. However, if I ...

Assigning a property to the Next.js response object

I recently discovered a fascinating concept involving setting an attribute on the response object within a Next.js API handler and being able to access that attribute in subsequent requests. This functionality took me by surprise as I couldn't find an ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

Issue with Website Rendering: Safari 4 exhibits display glitch showing temporary content before showing a blank white screen

Currently, I'm in the process of developing a specialized rails application. However, there seems to be an unusual rendering error that has been reported by Safari 4 users. It's quite peculiar because the page appears briefly but quickly disappea ...

Is it possible to use setState after a setTimeout to unmount a component?

Can anyone help me find the issue with my code? I am attempting to clear an error message after a specific duration, but it's not working as expected. I'm puzzled about what might be causing this problem. export default class MyError extends Com ...