[英]Angular form sends empty data
我從角度以表格形式將數據發送到服務器時遇到問題,我可以從數據庫獲取用戶當前數據並顯示它們,但我無法將數據發送回,而是發送空值。
playload of sending data to server
profile edit page with current data
HTML
<form [formGroup]="userUpdate" (ngSubmit)="update()" *ngIf="user">
<ion-item class="ion-margin-top">
<ion-label position="floating">Name</ion-label>
<ion-input type="text" [value]="user.name" formControlName="name"></ion-input>
</ion-item>
//rest of the fields
<ion-button class="ion-margin-top" type="submit" expand="full" color="success" >Update</ion-button>
</form>
profile.page.ts
export class ProfilePage implements OnInit {
public userUpdate: FormGroup;
imageURI: any;
user = null;
constructor(
private authService: AuthService,
private navCtrl: NavController,
private menu: MenuController,
private modalController: ModalController,
private alertService: AlertService,
private alertCtrl: AlertController,
public formBuilder: FormBuilder,
private camera: Camera,
) {
this.userUpdate = this.formBuilder.group({
name: ['', [Validators.required]],
username: ['', [Validators.required]],
email: ['', [Validators.email, Validators.required]],
password: ['', Validators.required],
phone: ['', [Validators.required]],
avatar: ['', [Validators.required]],
});
}
ngOnInit() {
this.menu.enable(true);
}
ionViewWillEnter() {
this.authService.getToken().then(() => {
if (this.authService.isLoggedIn) {
this.navCtrl.navigateRoot('/profile');
}
});
this.authService.user().subscribe((user: any) => {
this.user = user.success;
console.log('user success', user.success);
});
}
update() {
const userUpdate = this.userUpdate.value;
this.authService.update(
userUpdate.name,
userUpdate.username,
userUpdate.email,
userUpdate.password,
userUpdate.phone,
userUpdate.avatar = this.imageURI
).subscribe(
data => {
this.alertService.presentToast(data);
},
error => {
this.alertService.presentToast(error);
}
);
}
}
profile.service.ts
update(
name: String,
username: String,
email: String,
password: String,
phone: String,
avatar: String
) {
const headers = new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json',
'Authorization': 'Bearer' + " " + this.token.success.token
});
return this.http.post(this.env.BASE_URL + '/updateUser',
{
name: name,
username: username,
email: email,
password: password,
phone: phone,
avatar: avatar
}, { headers: headers }
);
}
知道為什么它發送空數據以及如何解決它嗎?
不要使用HTML值屬性設置用戶值,Angular反應形式控件的源是類,因此在html中設置值不會將值添加到formControl實例中。 如果要動態將Value設置為輸入字段,則可以使用setValue或patchValue方法。
this.authService.user().subscribe((user: any) => {
this.user = user.success;
this.userUpdate.patchValue({
name:user.name,
username: user.username ,//Assuming user object has username property
email: user.email,
password: user.password ,
phone: user.phone
});
console.log('user success', user.success);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.