2017-06-17 81 views
0

我對用戶添加和用戶編輯都使用相同的表單。如果用戶登錄,我知道即時編輯表單,如果用戶沒有登錄即時通訊添加新用戶。 即時通訊面臨的問題是,當用戶登錄時,我不得不查詢用戶數據的後端API來填寫表單,並且因爲GET請求是async表單已在我獲取數據之前創建。以下是我有:Angular2/4在請求後填充表單

ngOnInit() { 

    let userData = null; 

    if (this.userService.userId) { // user is logged in, query for data 
     this.http.get('http://localhost/api/user/get/' + this.userService.userId) 
      .subscribe(
      (data) => { 
       userData = data.json(); 
      }, 
      (error) => { 

      } 
    ); 
    } 

//init form 
this.form = new FormGroup({ 
    id: new FormControl(userData ? userData.id : ''), 
    name: new FormControl(userData ? userData.name : '', Validators.required) 
}); 

} 

一個解決方案,我認爲是複製的get塊的形式初始化後,我得到的數據,但這個dosent似乎是一個很好的解決方案,尤其是當表單初始化可以有很多領域。

這種情況下乾淨的解決方案是什麼?這裏

ngOnInit() { 
    let userData = null; 
    //init form 
    this.form = new FormGroup({ 
     id: new FormControl(userData ? userData.id : ''), 
     name: new FormControl(userData ? userData.name : '', Validators.required) 
    }); 


    if (this.userService.userId) { // user is logged in, query for data 
     this.http.get('http://localhost/api/user/get/' + this.userService.userId) 
     .subscribe(
      (data) => { 
      userData = data.json(); 
      this.form.patchValue({ 
       id: userData.id, 
       name: userData.name 
      }) 

      }, 
      (error) => { 

      } 
     ); 
    } 
    } 

注意,在發送GET請求之前FormGroup初始化 -

+0

您可以在成功請求時啓動表單。 – Ionut

回答

1

一個乾淨的解決問題的方法應該是這樣的。後來patchValue用於將新值綁定到formControlName

希望這會有所幫助。

+0

我很希望能夠避免樣板代碼,我必須首先初始化表單,然後分別修補每個值。如果表單有20多個字段,它可能會有點煩。但是這比我重新創建表單的解決方案還要好:) – user1985273

+0

實際上你不需要修補每個值,而只需要修改那些你想更新的值。其餘的將存儲舊的值:) – Abrar