[英]Angular get value from NgModel
我想將多個值從 a 發送到 API function。
在數據庫上,我以文本格式存儲值。 存儲的值是數組
在 Swal 警報中,我得到 [object object] 但我想獲得每個值,例如繪畫或圖形設計。
到目前為止,這是我的代碼。
HTML
<ion-item>
<ion-label>Painting</ion-label>
<ion-toggle color="gold" [(ngModel)]="creative.Painting" (click)="creativeInterest(creative)"></ion-toggle>
</ion-item>
<ion-item>
<ion-label>Graphic Design</ion-label>
<ion-toggle color="tertiary" [(ngModel)]="creative.Graphic Design" (click)="creativeInterest(creative)"></ion-toggle>
</ion-item>
.ts
export class CreativeSettingsPage implements OnInit {
creative: any = {};
userDetails: any = {};
constructor(
public userData: UserData
) {
this.userDetails = this.userData.getUserData();
}
ngOnInit() {
}
creativeInterest(creative:string)
{
this.userData.creativeSettings(this.userDetails.uid, creative).pipe(
map((data: any) => {
if (data.success) {
Swal.fire({
icon: 'success',
title: creative,
showConfirmButton: false,
backdrop: false,
timer: 2500
})
}
})
).subscribe()
}
用戶數據.ts
creativeSettings(uid: number, creative:any) {
const url = this.appData.getApiUrl() + 'creativeSettings';
const data = this.jsonToURLEncoded({
uid: uid,
creative: creative
});
return this.http.post(url, data, { headers: this.options });
}
PHP
function creativeSettings()
{
$request = \Slim\Slim::getInstance()->request();
$response['success'] = true; // 1 true if not errors OK NOTHING
$uid = $request->post('uid');
$creative_interests = $request->post('creative');
$db = getDB();
$sql = "UPDATE users SET creative_interests = :creative_interests WHERE uid = :uid";
$stmt = $db->prepare($sql);
$stmt->bindParam("uid", $uid);
$stmt->bindParam("creative_interests", $creative_interests);
$stmt->execute();
$db = null;
echo json_encode($response);
}
首先,在JS中命名object屬性時,通常的命名約定是camelCase。 例如:
creative.Painting
應該變成creative.painting
creative.Graphic Design
應該變成creative.graphicDesign
其次,您將整個creative
object 傳遞給 Swal,它需要一個字符串,這就是您得到[object Object]
的原因。 它不能自動假定要顯示哪個屬性,您需要明確 state 。 一種解決方案是將您想要顯示的標題作為creativeInterest(creative:string)
方法的參數傳遞,即:
creativeInterest(creative:string, messageTitle: string)
{
this.userData.creativeSettings(this.userDetails.uid, creative).pipe(
map((data: any) => {
if (data.success) {
Swal.fire({
icon: 'success',
title: messageTitle,
showConfirmButton: false,
backdrop: false,
timer: 2500
})
}
})
).subscribe()
}
並在您的組件標記中(下面的代碼段中省略了未更改的部分):
<ion-toggle color="gold" [(ngModel)]="creative.painting" (click)="creativeInterest(creative, 'Painting')"></ion-toggle>
<ion-toggle color="tertiary" [(ngModel)]="creative.graphicDesign" (click)="creativeInterest(creative, 'Graphic Design')"></ion-toggle>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.