【问题标题】:How to bind like button in array list using ionic 4?如何使用 ionic 4 在数组列表中绑定类似按钮?
【发布时间】:2019-07-22 14:55:06
【问题描述】:

我有一个数组列表,在列表中,每个项目都有一个带有类似计数的类似按钮。现在一个系统就像当我点击喜欢按钮时,我得到回报 1 表示喜欢,但对于更改显示,我正在调用 API 并刷新页面,但我想在不刷新页面的情况下显示更改,其他社交媒体应用程序正在工作/正在运行。为此,我又创造了一个价值作为回报,例如 count for ex。当用户点击赞按钮时,它将返回 1 表示赞的总数。

homePage.ts

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);
    });
});
}

主页.html

<div (click)="openfeedDetails(feed.PostId)" *ngFor="let feed of feedlist">
<ion-col tappable>
    <ion-icon class="liked" (click)="toggleLikeState(feed.UserId,feed.PostId);$event.stopPropagation();"
        tappable name="{{feed.IsLike ? 'heart' : 'heart-empty'}}">
    </ion-icon>&nbsp;&nbsp;
    <span *ngIf="feed.LikesCount > 0">{{feed.LikesCount}}</span>
</ion-col>
</div>

请帮忙...

【问题讨论】:

    标签: angular ionic-framework


    【解决方案1】:

    我不确定您需要刷新页面以反映页面 likeCount 和 likeState 的意思。 然而,为了优化你的代码,因为在 JS 中对象被访问by reference,所以如果你修改了被点击的 feed 的 likeState 和 likeCount,它会在 UI 中自动更新,因为angular bind。除非您希望用户始终看到来自服务器的最新状态,否则您不必从服务器重新获取整个提要。

        <ion-icon class="liked" (click)="toggleLikeState(feed);$event.stopPropagation();"
            tappable name="{{feed.IsLike ? 'heart' : 'heart-empty'}}">
        </ion-icon>
    
       toggleLikeStates(feed: Feed) {
        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("success", success);
              feed.IsLike = !feed.IsLike;
              feed.IsLike ? feed.LikesCount++ : feed.LikesCount--;
            }, (error) => {
              console.log("Error", error);
            });
        });
        }
    

    注意:类名和属性名请分别遵循pascal大小写和camel大小写的JS命名标准

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      相关资源
      最近更新 更多