如何在无表单情况下通过点击事件将星级评分值传递至TypeScript文件
解决方案:传递星级评分到TypeScript并保存到数据库
咱们直接来搞定这个需求——把用户选中的星级评分传到TypeScript组件,再通过HTTP请求存到数据库。我会分步骤给你梳理清楚:
1. 完善对话框模板(HTML)
先给你的模板补上提交按钮,绑定点击事件,同时把星星符号补全,明确10星的最大值:
<h2 mat-dialog-title>Rate sitter {{ sitter.firstname }} {{ sitter.lastname }}</h2> <mat-dialog-content class="mat-body-1"> <ngb-rating [(rate)]="currentRate" [max]="10"> <!-- 明确设置为10星系统 --> <ng-template let-fill="fill"> <span class="star" [class.filled]="fill">★</span> <!-- 完整的星星符号 --> </ng-template> </ngb-rating> <p class="mt-2">当前选中评分: {{ currentRate }}</p> <!-- 可选:让用户直观看到选中的星级 --> </mat-dialog-content> <mat-dialog-actions align="end"> <button mat-button (click)="closeDialog()">取消</button> <button mat-button color="primary" (click)="submitRating()">提交评分</button> </mat-dialog-actions>
2. 编写TypeScript组件逻辑
在对话框的TS文件里,咱们定义变量接收评分,实现提交方法和HTTP请求:
import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-rating-dialog', templateUrl: './rating-dialog.component.html', styleUrls: ['./rating-dialog.component.css'] }) export class RatingDialogComponent { currentRate = 0; // 初始化默认评分为0 constructor( private dialogRef: MatDialogRef<RatingDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: { sitter: any }, // 接收传入的 sitter 数据 private http: HttpClient ) {} closeDialog(): void { this.dialogRef.close(); } submitRating(): void { // 简单校验:确保用户选了评分 if (this.currentRate === 0) { alert('请选择一个星级评分哦'); return; } // 组装要传给后端的数据 const ratingPayload = { sitterId: this.data.sitter.id, // 假设 sitter 对象有 id 字段 rating: this.currentRate, // 可以额外加用户ID、评分时间等字段 }; // 发送HTTP POST请求到后端接口 this.http.post('/api/sitters/rating', ratingPayload).subscribe({ next: (res) => { console.log('评分保存成功!', res); this.dialogRef.close(true); // 关闭对话框并返回成功状态 }, error: (err) => { console.error('保存评分失败', err); // 这里可以换成更友好的提示,比如Angular Material的Snackbar alert('保存评分失败,请稍后重试'); } }); } }
关键细节说明
- 双向绑定省心省力:
[(rate)]="currentRate"是ng-bootstrap的双向绑定语法,用户选星的时候,currentRate会自动同步更新,不用手动写事件监听。 - 对话框传数据:通过
MAT_DIALOG_DATA注入拿到父组件传过来的sitter对象,这样就能把 sitter 的ID和评分一起传给后端,确保数据关联正确。 - HTTP请求处理:用Angular自带的
HttpClient发POST请求,替换成你实际的后端接口地址就行,成功和失败的回调里可以加对应的用户反馈,提升体验。
内容的提问来源于stack exchange,提问作者CodeHip
相关产品推荐
相关产品推荐

