需要正确地迭代我的图片数组angular 2

时间:2018-09-26 17:14:13

标签: javascript arrays angular typescript

所以我有这个功能,它是“下一个”按钮,应该转到数组中的下一张图片。我还有一个“上一个”按钮,该按钮具有基本相同的代码,但不是将索引加1而是将其减去1。但是,这将无法正常工作。当我按下next按钮时,它会自动转到数组中的最后一张图片,而看不到下一张图片。我以为可能使用了pop方法,但是我不确定,这很新

export class PictureModalComponent {
  model = {
    servNum: '',
    servDate: '',
    caption: '',
    url: '',
    id: null,
    pictures: []
  };

  constructor(@Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<PictureModalComponent>) {
    this.model=data;
  }

  onPreviousClick() {
    this.model.pictures.forEach( (picture: AccessApictures, index: number) => {
      if (picture.id === this.model.id)
        {
          let lastPicture: AccessApictures = this.model.pictures[index-1];
          this.model.caption = lastPicture.caption;
          this.model.servDate = lastPicture.servDate;
          this.model.servNum = lastPicture.aservrecno;
          this.model.url = lastPicture.filename;
          this.model.id = lastPicture.id;
        }
    });
  }

  onNextClick() {

    this.model.pictures.forEach( (picture: AccessApictures, index: number) => {
      if (picture.id === this.model.id ) {
        let nextPicture: AccessApictures = this.model.pictures[index+1];

        this.model.caption = nextPicture.caption;
        this.model.servDate = nextPicture.servDate;
        this.model.servNum = nextPicture.aservrecno;
        this.model.url = nextPicture.filename;
        this.model.id =  nextPicture.id;
      }
    }); 
  }
}

1 个答案:

答案 0 :(得分:0)

创建一个index变量应该可以消除昂贵的循环,从而为您提供帮助。它基本上是2个字节,可以节省您的性能。

index = 0;
model = {
   servNum: '',
   servDate: '',
   caption: '',
   url: '',
   id: null,
   pictures: []
};

constructor(@Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<PictureModalComponent>) {
  this.model = data;
  data.pictures.forEach((pic, index) =>  {
     if (pic.id === data.id) {
       this.index = index;
       break;
    }
  }
}

// update index with looping to the last picture if on first
onPreviousClick() {
  this.index = this.index === 0 ? this.model.pictures.length - 1 : this.index - 1;
  this.updateModel(this.model.pictures[this.index]);
}

// updating index with looping to the first picture if on last
onNextClick() {
  this.index = this.index === this.model.pictures.length - 1 ? 0 : this.index + 1; 
  this.updateModel(this.model.pictures[this.index]);
}

// common logic into a single function
updateModel(pic: AccessApictures) {
  this.model.caption = pic.caption;
  this.model.servDate = pic.servDate;
  this.model.servNum = pic.aservrecno;
  this.model.url = pic.filename;
  this.model.id = pic.id;
}