0

I need to display and edit list of items returned by a http service in Angular 4 Reactive form. Since I have indefinite list, I need FormArray. but my problem is my http service which returns an observable is not supplying data when I am patching the array. So when I am looping through the returned data set, It throws error 'Cannot read property x of undefined'. I am new to Observable so I couldn't figure out the solution. Could you please help?

service:

getCountries() : Observable<Country[]>{
    console.log('In getCountries');
    return this.http
        .get(this.apiUrl)
        .map(response => <Country[]>response.json());
}

Component:

ngOnInit(){
    this.getCountries();
    this.initForm();
    this.patchForm();
}

getCountries(){
    this.countryService.getCountries()
    .subscribe( response => {
        this.countries = response;
        console.log('response');
        console.log(response);
    },
    error => {
        console.log('error');
        console.log(error);
    });
    console.log('this.countries');
    console.log(this.countries);
}

patchForm(){
    const control = <FormArray>this.countryForm.controls.countries;
    console.log('in patchForm()');
    console.log(this.countries);
    this.countries.forEach(element => {
        control.push(this.formBuilder.group({
            id: element.id,
            name: element.name,
            deleted: element.deleted
        }));
    });
}

the response from getCountries() is getting displayed in the browser console at the end. Seems I am missing some asynchronous concept here.

1 Answers1

0

You need to move patchForm inside of success callback of your Observable

ngOnInit(){
    this.initForm();
    this.getCountries();
}

getCountries(){
    this.countryService.getCountries()
    .subscribe( response => {
        this.countries = response;
        this.patchForm();
        console.log('response');
        console.log(response);
    },
    error => {
        console.log('error');
        console.log(error);
    });
    console.log('this.countries');
    console.log(this.countries);
}
A. Tim
  • 3,046
  • 1
  • 13
  • 15