Angular 4 FormArray在http Observable Service中有延迟

时间:2017-07-21 14:16:31

标签: angular rxjs observable

我需要以Angular 4 Reactive形式显示和编辑http服务返回的项目列表。由于我有无限列表,我需要FormArray。但我的问题是我的http服务返回一个observable在我修补数组时没有提供数据。因此,当我循环遍历返回的数据集时,它会抛出错误'无法读取未定义的属性x'。我是Observable的新手,所以我无法找到解决方案。你能帮忙吗?

服务:

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

组件:

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
        }));
    });
}

getCountries()的响应最终会显示在浏览器控制台中。似乎我在这里错过了一些异步概念。

1 个答案:

答案 0 :(得分:0)

您需要在patchForm

success回调中移动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);
}