我有一个动态的帖子列表。在每篇文章中,我添加了一个"喜欢"和一个"注释"按钮。我的问题是,当我单击"喜欢"按钮时,我必须手动重新加载页面以显示更改。
我想到的一种解决方案是在类似按钮的(click)
事件中添加API调用,以便重新加载页面,但这看起来不好。
page.html
<ion-col *ngIf="feed.IsLike" tappable>
<ion-icon (click)="toggleLikeState(feed.UserId, feed.PostId);$event.stopPropagation();" tappable
name="heart"></ion-icon>
<span *ngIf="feed.LikesCount > 0">{{feed.LikesCount}}</span>
</ion-col>
<ion-col *ngIf="!feed.IsLike" tappable>
<ion-icon (click)="toggleLikeState(feed.UserId, feed.PostId);$event.stopPropagation();" tappable
name="heart-empty"></ion-icon>
<span *ngIf="feed.LikesCount > 0">{{feed.LikesCount}}</span>
</ion-col>
page.ts
toggleLikeState(UserId: number, PostId: number) {
this.storage.get('userID').then(async (loggedinUId) => {
const value: {
LoginUserId: string,
UserId: number,
PostId: number
} = {
LoginUserId: loggedinUId,
UserId: UserId,
PostId: PostId
};
this.apiService.postLike(value).then(async (success) => {
console.log("succ", success);
if (success = 0) {
console.log(success);
this.IsLike = !this.IsLike;
this.apiService.getPostsfeeds().then((data: any[]) => {
this.feedlist = data;
});
if (this.IsLike) {
this.iconName = 'heart';
} else {
this.iconName = 'heart-empty';
}
} else {
this.IsLike = !this.IsLike;
this.apiService.getPostsfeeds().then((data: any[]) => {
this.feedlist = data;
});
if (this.IsLike) {
this.iconName = 'heart';
} else {
this.iconName = 'heart-empty';
}
}
}, error => {
console.log("Error", error);
});
});
}
Here my code, is there any way to display like's without reloading the page or I have to user socket.io?
好吧,对于初学者,您可以使用三元运算符而不是 *ngif指令来改善HTML视图。您只能在图标的名称上应用此标记,因为其余的标记将保留在两种情况下。
{{ condition? 'conditionWasTrue' : 'conditionWasFalse' }}
是在一行中写入if-else的好方法,那么您的HTML代码看起来像这样:
<ion-col tappable>
<ion-icon (click)="toggleLikeState(feed.UserId,feed.PostId);$event.stopPropagation();"
tappable name="{{feed.IsLike ? 'heart' : 'heart-empty'}}">
</ion-icon>
<span *ngIf="feed.LikesCount > 0">{{feed.LikesCount}}</span>
</ion-col>
然后,在您的打字稿文件中,您将不再需要" ICONNAME"变量,因此您可以删除其中的很大一部分,并且它将开始看起来更清洁。更好的是,您可以在函数范围之外移动接口声明:
编辑:如果要更新喜欢的数量而不刷新视图,则需要在apiService.postLike()
方法的响应中返回新数量的赞。
更新后端API以包括Postlike((成功时都包括新的LikesCount,您可以使用新的response.LikesCount
属性来更新组件的内部变量:
interface UserLikedPost {
LoginUserId: string,
UserId: number,
PostId: number
}
toggleLikeState(UserId: number, PostId: number) {
this.storage.get('userID').then(async (loggedinUId) => {
const value: UserLikedPost = {
LoginUserId: loggedinUId,
UserId: UserId,
PostId: PostId
};
this.apiService.postLike(value).then(
async (success) => {
console.log("succ", success);
this.IsLike = !this.IsLike;
this.feed.LikesCount = success.LikesCount; // Here is where you update your likes without refreshing.
this.apiService.getPostsfeeds().then((data: any[]) => {
this.feedlist = data;
});
}, (error) => {
console.log("Error", error);
});
});
}
每当您想使用新信息更新屏幕视图时,您都需要执行API调用,但不需要看起来那么糟糕。希望这对您有帮助!