angular - 通过将特定条件放在数组对象上,在模板文件中显示特定值
问题描述
我有一组对象,我想从中显示 html 文件上的特定文本。
条件是:
- 如果用户订阅,则显示文本“自动”
- 如果用户未通过验证,则文本“试用”
- 如果用户通过验证并订阅,则文本“免费”
- 如果用户订阅已结束,则文本“已过期”
- 如果用户订阅由管理员延长,则文本“手动”
对于订阅,我在数据库中管理名为 payment_details 的数组。对于在数据库中调用的经过验证的管理布尔字段
我无法在前端为这些创造条件。所以我在 ts 文件中尝试了。但它占用了数组的最后一个元素。
模板文件:
<tr class="table-rows-customized" *ngFor="let therapist of therapistlist | filter : searchText" >
<td class="td-data pointer" (click)="therapistdetails(therapist._id);">
<img *ngIf="!therapist.profilepic" src="assets/img/users/user.jpg" class="user-image" alt="">
<img *ngIf="therapist.profilepic" [src]="therapist.profilepic" class="user-image" alt="">
{{ therapist.fullname }}
</td>
<td class="td-data">{{ type.id === therapist._id ? type.text : '' }}
</td>
</tr>
ts文件:
this.therapistlist.map((therapist) => {
if(therapist.payment_details) {
if(therapist.payment_details.length && therapist.verifiedBadge) {
this.type = {
text: 'free',
id: therapist._id
}
}
if(therapist.payment_details.length) {
if(therapist.payment_details[0].paymentType == 'Cash') {
this.type = {
text: 'manual',
id: therapist._id
}
}
if(therapist.payment_details[0].paymentType == 'Credit Card') {
this.type = {
text: 'auto',
id: therapist._id
}
}
}
}
if(moment(therapist.premimumEndDate).isAfter(moment())) {
this.type = {
text: 'expired',
id: therapist._id
}
}
})
console.log('map.... ', this.type);
从上面的代码我没有得到任何东西,并且在日志中我得到了空值。
解决方案
.map 函数将遍历数组中的每个元素并根据您的条件计算类型。但是您的 console.log 在迭代器之外,它总是会获取数组中最后一项的类型。
您需要分配和记录,或者根据需要使用 .map 函数中的类型对象。这样,您将拥有初始数组中每个对象的特定类型。
this.therapistlist.map((therapist) => {
this.type = {
id: therapist._id,
text: 'default'
}
if (therapist.payment_details) {
if (therapist.payment_details.length && therapist.verifiedBadge) {
this.type.text = 'free';
} else if (therapist.payment_details.length) {
if(therapist.payment_details[0].paymentType === 'Cash') {
this.type.text = 'manual';
} else if (therapist.payment_details[0].paymentType === 'Credit Card') {
this.type.text = 'auto';
}
}
}
if (moment(therapist.premimumEndDate).isAfter(moment())) {
this.type.text = 'expired';
}
console.log(this.type);
});
我还重构了您的代码,因为其中一个条件是重叠的。
如果满足第一个条件,那么第二个条件也将满足。
if(therapist.payment_details.length && therapist.verifiedBadge)
if(therapist.payment_details.length)
最后就像现在一样,如果订阅过期,无论类型是什么,它都会始终更改类型。
推荐阅读
- java - 如何在 Spring JDBC 中启用 sql 查询控制台日志记录
- react-native - 如何在本机反应中使用 EXPO 应用程序?
- rust - 如何使用参数来索引 rust 中的数组?
- swift - 在 SwiftUI 中有条件地使用视图
- java - ecplise 中的 libGDX android 和 html 文件夹中的代码错误
- bash - 加入命令未显示预期结果
- java - 未处理的异常在两种不同的方法上的工作方式不同
- git - 如何使用来自 git 的版本信息自动设置 gradle build?
- php - 如何将以前的余额添加到报表中的运行总计
- php - Laravel:如何使用工厂以特定模式播种模型?