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?