我有动态的帖子列表。在每个帖子中,我都添加了一个“喜欢”和“评论”按钮。我的问题是,当我单击“赞”按钮时,我必须手动重新加载页面才能显示更改。
我想到的一个解决方案是在like按钮的(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?
答案 0 :(得分:1)
好吧,对于初学者,您可以使用三元运算符而不是* 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>
然后在您的typeScript文件中,您不再需要“ iconName”变量,因此您可以擦除其中的大部分内容,并且它将看起来更干净。更好的是,您可以将接口声明移出函数范围之外:
编辑:如果您想在不刷新视图的情况下更新点赞次数,则需要在apiService.postLike()
方法的响应期间返回新的点赞次数。>
在postLike()成功后更新后端API以包括新的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调用,但是看起来不需要那么糟糕。希望这对您有所帮助!