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

时间:2017-04-05 03:10:48

标签: angular ionic-framework ionic2

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

我面临的问题是,在使用数据在组件上设置属性时,我仍然无法调用Slides.slideTo(),因为组件尚未更新,我不知道正确这样做的时机。我也没有看到可以绑定到幻灯片组件上的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?

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

更新

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

1 个答案:

答案 0 :(得分:0)

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

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