Angular中实现无评论时展示‘暂无评论’提示的需求
解决无评论用户的「暂无评论」提示问题
问题根源
当前代码仅在reviews数组有数据时渲染评论列表,当无评论时数组为空,页面就没有任何内容展示。需要添加空状态的提示逻辑,同时完善请求处理避免数据残留。
第一步:完善TS的getReviews方法
确保请求前后数据状态清晰,处理空数据和异常情况:
getReviews(data: any) { // 先清空历史数据,避免旧评论残留 this.reviews = []; this.rating = ''; this.total_rating = ''; this.ds.getReviews(data).subscribe( (resp: any) => { if (resp.status == true) { // 确保接口返回空数据时,数组不会为undefined this.reviews = resp.data || []; this.rating = resp.rating; this.total_rating = resp.total_rating; } else { // 接口返回失败状态时,也置空评论数组 this.reviews = []; } }, (error) => { // 请求出错时,置空数组并提示(可选) this.reviews = []; this.ts.error('获取评论失败'); } ); }
第二步:修改HTML添加空状态提示
在评论列表容器后,添加当评论为空时显示的提示,同时修正原代码的拼写错误(çontainer改为container):
<div class="checkbox-item mt-2" (click)="getReviews(item.offer_by.id)"> <button type="button" class="btn btn-outline-secondary" >Reviews</button> </div> <!-- 评论列表 --> <div class="container" *ngFor="let items of reviews" > <div class="row"> <h6>{{items.name}}</h6> <div class="emVaRl"> <div class="lnfldP"> <svg width="16" height="16" class="elJCm" viewBox="0 0 24 24" *ngFor='let in of counter(items.review_rating) ;let i = index'> <path d="M16.2 8.16l4.74.73a1.23 1.23 0 01.67 2.11l-3.46 3.28a1.23 1.23 0 00-.37 1.1l.77 4.68a1.24 1.24 0 01-1.82 1.29L12.5 19.1a1.28 1.28 0 00-1.16 0l-4.27 2.17A1.25 1.25 0 015.27 20l.85-4.68a1.19 1.19 0 00-.34-1.09l-3.41-3.4a1.23 1.23 0 01.71-2.1l4.75-.64a1.26 1.26 0 00.95-.67l2.16-4.24a1.25 1.25 0 012.24 0l2.09 4.28a1.22 1.22 0 00.93.7z"> </path> </svg> </div> </div> <p>({{items.review}})</p> <hr> </div> </div> <!-- 暂无评论提示 --> <div class="container" *ngIf="reviews.length === 0"> <div class="row text-center text-muted"> <p>暂无评论</p> </div> </div>
备注:移除了原代码中多余的
*ngIf="items.tasker_id == item.offer_by.id"判断——因为getReviews是根据当前用户ID请求的评论,返回的结果必然属于该用户,这个判断会导致不必要的渲染限制。
内容的提问来源于stack exchange,提问作者Team Thunder
相关产品推荐
相关产品推荐

