2017-02-28 60 views
1

我有一個表格。當用戶沒有任何信息時,他會輸入一些信息併發送一個POST請求來保存他的數據。當用戶有關於他自己的信息時,該頁面顯示他的信息並且表單提交應該發送一個PUT請求來更新數據。如何從同一表單發送PUT/POST請求?

這怎麼能實現?

+1

嗯這個問題說得很奇怪,因爲如果一個用戶瀏覽他的頁面,他怎麼沒有信息?即使空白,他也應該有信息。我的觀點是,該方法可能應該始終是PUT,但我很挑剔。除此之外,也許可以通過編程方式更改'method'的形式嗎? – JSelser

+0

@JSelser謝謝你的建議。 –

回答

2

讓您有一個配置文件形式:

profilebuilder() { 
    this.profileForm = this.formBuilder.group({ 
     'email': ['', [Validators.required], 
     'firstName': ['', [Validators.required]], 
    } 

,並用GET方法獲取用戶數據:

getprofile() { 
    let url = this.global_service.base_path + 'something...'; 
    this.global_service.GetRequestAuthorised(url) 
     .subscribe(res => { 
     this.Userinfo = res[0].json.data; 
     this.setFormValue(); 
     }, 
     err => { 
     console.log("data not found"); 
     }, 
    () => { 

     }) 
    } 

調用setformvalue(),這將automaticall如果用戶的數據更新表單有:

setFormValue() { 
     this.profileForm.controls['email'].setValue(this.Userinfo.email); 
     this.profileForm.controls['firstName'].setValue(this.Userinfo.firstName); 
     } 

然後使用PUT請求來更新您的表單:

saveprofile(formdata) { 
    let url = this.global_service.base_path + 'something...'; 

    this.global_service.PutRequest(url, formdata) 
     .subscribe(res => { 
     if (res[0].status == 200) { 
      this.getprofile(); 
     } 
     }, 
     err => { 
     console.log(err, ' error'); 
     }, 
    () => { 

     }) 
    } 
1

您可以定義一個變量來標記服務器是否有當前用戶的數據。當用戶發送信息時,檢查變量以確定是使用POST還是PUT。