Angular从NgModel获取值



我想将多个值从发送到API函数。

在DB上,我以文本格式存储值。存储的值是数组

在Swal警报中,我得到了[对象对象],但我想得到每个值,例如绘画或平面设计。

这是我迄今为止的代码。

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 = SlimSlim::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中命名对象属性时,通常的命名约定是camelCase。例如:

creative.Painting应成为creative.painting

creative.Graphic Design应成为creative.graphicDesign

其次,您将整个creative对象传递给Swal,它需要一个字符串,这就是为什么您得到[object Object]的原因。它不能自动假设显示哪个属性,您需要明确声明。一种解决方案是传递要显示为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>

最新更新