等待从本地存储中检索数据

问题描述 投票:0回答:1

当图库加载到我的图库应用中时,会调用一个函数来检查当前用户是否喜欢图像数组中的图像。如果用户喜欢该图像,则在图像上方会显示一个实心图标。如果不喜欢该图像,则会显示心脏轮廓图标。

在函数内,我们获得用户数组中的当前用户索引。该信息是从存储在浏览器本地存储中的用户对象检索的。我遇到的问题是在从本地存储中检索用户数据之前调用了该函数,并且我不确定如何解决此问题?

这里是图库列表组件中的相关html:

<div class="gallery-container">
    <div
      class="image-container"
      *ngFor="let image of galleryList">
      <div *ngIf="checkLike(image.imagePath)" class="heart-icon-container">
        <ion-icon name="heart" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
      </div>
      <div *ngIf="!checkLike(image.imagePath)" class="heart-icon-container">
        <ion-icon name="heart-outline" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
      </div>
    </div>
</div>

这里是图库列表ts文件中的相关代码:

  currUsersIndex: number;

ngOnInit() {

    this.currUsersIndex = this.usersService.getCurrUserArrIndex();

}



 checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();

    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;

      if(FavouritesList.includes(imageUrl)) {
          return true;
      } else {
          return false;
      }
  }
    }

最后,这是从users.service文件中检索用户索引的位置:

private users: User[] = [];
 getCurrUserArrIndex() {

        const usersEmail = this.getCurrentUser().email;

        const users = this.getUsers();

        const usersIndex = users.findIndex(user => user.email === usersEmail);

        return usersIndex;

        }


 getCurrentUser() {

    const userData: {

         email: string,
         id: string,
         _token: string,
         _tokenExpirationDate: string

     } = JSON.parse(localStorage.getItem('authUserData')); 

 return userData;

 }



    getUsers() {
        return this.users.slice();
    }

请注意,用户数组最初设置为空,但在应用初始化时,它是与firebase数据库中的用户一起设置的。

我在控制台中收到的错误消息是:"can't access property "likes", users[this.currUsersIndex] is undefined"

javascript angular
1个回答
0
投票

我认为,这里的问题是,在HTML中调用this.currUsersIndex时未设置checkLike()

或者,我可以向您推荐的是,在组件中定义一个布尔变量,

checkLike = false;

然后在设置[currUsersIndex]之后调用函数checkLike()

ngOnInit() {
    this.currUsersIndex = this.usersService.getCurrUserArrIndex();
    this.checkLike();
}

checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();
    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;
      if(FavouritesList.includes(imageUrl)) {
          this.checkLike = true;
      } else {
          this.checkLike = false;
     }
  }

您必须已经在component.ts中有了imageUrl,只需替换为它。

© www.soinside.com 2019 - 2024. All rights reserved.