2016-11-23 24 views
0

的問題首先檢索數據以設置默認表單值? (Angular2)

我設置了一個相當複雜的形式,每一次我提交補丁請求重置價值爲null。

在當我嘗試設置默認值在它不會工作的服務加載的數據,由於數據不可馬上表單控件/尚未保存到public model = Model[]

守則

getControls() { 
    let controlObj = {} 

    for (var i = 0; i <= 7; i++) { 
     this.field1 = "field-1-" + i 

     testObj[this.field1] = new FormControl({value: this.model.name}, Validators.required) 

    } 
    this.controls = testObj 
    return this.controls; 
    } 



    ngOnInit() { 

    this.myService.getData() 
     .subscribe(
     settings => { 
      this.model = model; 
      console.log(this.model) 

     }, 
     error => console.error(error) 
     ) 

    console.log(this.model) 


    this.settingsForm = new FormGroup(
     this.getControls() 
    ) 

    } 

} 

摘要

new FormControl({value: this.model.name}不能檢索此值作爲服務d oes不保存要在組件內再次使用的數據。

在運行其餘函數之前,我有沒有辦法讓保存從組件獲取請求中獲取的信息?

我有點困惑,爲什麼console.log(this.modal)裏面的服務請求返回的數據,但外面的一個返回null。

讓我知道如果你需要更多的代碼 - 我試圖擺脫最低限度避免混淆。謝謝!

回答

1

我有點困惑,爲什麼服務請求中的console.log(this.modal)返回數據,但外部返回null。

因爲它是異步處理。

console.log(this.model)外部subscribe可能會先執行,然後this.model接收到任何值,這就是爲什麼它顯示爲空。

如果你想getControls執行this.model具有價值後,再更改您的代碼

ngOnInit() { 
    this.myService.getData() 
     .subscribe(
     settings => { 
      this.model = model; 
      this.settingsForm = new FormGroup(
       this.getControls() 
      ) 
     }, 
     error => console.error(error) 
     ); 
} 
+0

我沒想到,最初,但它不工作,(想出了一個模板錯誤),所以不得不換我在ngIf內部形成,並在調用訂閱中的this.getControls()後觸發它。我不確定爲什麼最初嘗試時它不工作,但感謝您的答案!它有效,也許我的訂購是錯誤的。謝謝 ! – confusedandenthused