繁体   English   中英

如何在设置数据后立即将具有动态幻灯片数量的Ionic 2幻灯片组件移动到某个幻灯片?

[英]How to make Ionic 2 Slides component with dynamic number of slides move to some slide right after setting the data?

我需要使用*ngFor动态地从我使用HTTP请求获得的数据设置Ionic 2幻灯片组件的幻灯片,并使其特定幻灯片设置为活动状态。

我面临的问题是,在使用数据在组件上设置属性时,我仍然无法调用Slides.slideTo()因为组件尚未更新,我不知道正确的时间那。 我也没有看到可以绑定到Slides组件上的activeSlide等属性。

这是描述我尝试过的代码:

<ion-slides>
  <ion-slide *ngFor="let obj of myObjects">
    <div>{{ obj.title }}</div>
  </ion-slide>
</ion-slides>

this.http.get('http://example.com', options)
.toPromise()
.then(response => {
    this.myObjects = response.json() as MyObject[];
    this.currentObject = this.myObjects.find(obj => obj.is_selected);

    // Get the index of the slide I want to set as active.
    let index = this.myObjects.indexOf(this.currentObject);

    // Set it as active -- doesn't work here, because this.slides isn't updated yet.
    this.slides.slideTo(index, 0);

    // I tried using ChangeDetectorRef.detectChanges() and looked at 
    // the length of slides, but it seems that it doesn't run change 
    // detection immediately.
    // 
    // this.ref.detectChanges();
    // console.log(this.slides.length()) // returns 0

    // Calling Slides.update() after the detectChanges() doesn't help.
    // 
    // this.slides.update();
    // console.log(this.slides.length()) // still 0

    // I tried setTimeout(callback, 0) to run this after the stack is empty
    // and presumably the change detection has run, but still no dice.
    // 
    // setTimeout(() => {
    //     console.log(this.slides.length());
    // }, 0); // doesn't work

    // What is interesting, but also a bit disturbing, is that setting
    // the timeout to some other value sometimes returns a value
    // indicating that a change detection has run and sometimes it's 
    // still 0. The longer the timeout, the more probable it runs after 
    // the change detection, but I noticed that up to 20ms I never got 
    // anything else than 0, but at 25ms I tend to get proper values 
    // (but not always). I'm running this on Android device with 
    // Visual Studio Code's default configuration "Run Android on device".
    // 
    // setTimeout(() => {
    //  console.log(this.slides.length());
    // }, 25); // sometimes works
})

使用Vue框架我曾经在这种情况下使用Vue.nextTick() ,但由于setTimeout(callback, 0)似乎不起作用,我应该如何使用Angular 2处理它?

我正在使用Ionic 2.2.0(Angular 2.4.8)和Cordova 6.5.0。 任何见解都会非常受欢迎。

UPDATE

我发现了一个可能相关的离子问题: https//github.com/driftyco/ionic/issues/6703

如果您在ionViewDidEnter()内部进行调用,则slideTo函数将按预期工作,例如:

ionViewDidEnter(){
    this.slides.slideTo(this.index,0);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM