2016-10-04 49 views
0

在Chrome控制檯中出現錯誤:EXCEPTION:錯誤:未捕獲(承諾中):TypeError:無法讀取屬性'applicationName'爲null。使用空值填充FormGroup和

型號: 出口類BasicInfoModel {

applicationName: string; 
    localDirectoryPath: string; 
} 

控制器發射數據到父組件,有父組件它被保存到服務。

控制器:

import { Component, Output, OnInit, EventEmitter} from '@angular/core'; 
import { FormGroup, FormControl, REACTIVE_FORM_DIRECTIVES, Validators,    
FormBuilder, FormArray}from "@angular/forms"; 
import { Observable } from "rxjs/Rx"; 
import { BasicInfoModel } from '../basicinfomodel'; 
import { BasicInfoService} from '../app.dev.basicinfo.service'; 

@Component({ 
    selector: 'basic-info', 
    templateUrl: './basicInfo.html', 
    styleUrls: ['../../ComponentStyles.css'], 
    directives: [REACTIVE_FORM_DIRECTIVES] 
}) 

export class BASIC_INFOComponent implements OnInit { 

observableBasic: BasicInfoModel; 
basicInfoForm: FormGroup; 

@Output() basicInfoUpdate = new EventEmitter<JSON>(); 
@Output() basicInfoFormValid = new EventEmitter<Boolean>(); 

constructor(private formBuilder: FormBuilder, private BasicInfoService:  
BasicInfoService) { } 

onSubmit() { 
    debugger; 
    this.observableBasic; 
    this.basicInfoUpdate.emit(this.basicInfoForm.value); 
} 

ngOnInit() { 

    this.basicInfoForm = new FormGroup({ 
     'applicationName': new FormControl('', Validators.required), 
     'localDirectoryPath': new FormControl('', Validators.required) 
    }); 

    this.basicInfoForm.valueChanges.subscribe(data => console.log('form 
    changes', data)); 
    this.BasicInfoService.currentBasicInfo 
     .subscribe(
     (basic: BasicInfoModel) => { 
      this.observableBasic = basic; 
     }); 

    (<FormGroup>this.basicInfoForm).setValue(this.observableBasic, { onlySelf: true }); 
} 

} 

我想達到的目標:

  1. 當我建立我的代碼,我想我應該formGroup空值來填充。
  2. 當我填充數據並將其保存到我的服務中的behaviourSubject時,後者當我重新訪問該頁時,我的formGroup應該與數據服務同步。

回答

0

通過將修改了的Controler:(!this.observableBasic =未定義)

ngOnInit() { 
    this.basicInfoForm = new FormGroup({ 
     'applicationName': new FormControl('', Validators.required), 
     'localDirectoryPath': new FormControl('', Validators.required) 
    }); 

    this.BasicInfoService.currentBasicInfo 
     .subscribe((basic: BasicInfoModel) => { this.observableBasic = basic; }); 

    if (this.observableBasic != undefined) { 
     (<FormGroup>this.basicInfoForm).setValue(this.observableBasic, { onlySelf: true }); 
    }  

    this.basicInfoForm.valueChanges.subscribe(data => console.log('form changes', data)); 
}