Error when using virtual Scroll for displaying data fetched with http request

I am trying to use virtual scroll in Ionic 2. The virtual scroll should show the elements fetched by a http request. When using *ngFor everything works out fine but when using virtual scroll I get the Error:

browser_adapter.js:77 TypeError: Cannot read property ‘indexOf’ of undefined

HTML:

 <ion-list [virtualScroll]="posts" *ngIf="!cantDoRequest">
            <ion-div *virtualItem="#post">
                <ion-item-sliding *ngIf="post.bereich.indexOf('CallCenter')>-1 && callc == 'true'">
                    <button ion-item text-wrap (click)="itemTapped($event, post)" *ngIf="post.bundesland.indexOf('Baden-Württemberg')>-1 && baden == 'true'">
...

JS:

import {Platform, Page, NavController, NavParams, Storage, SqlStorage} from 'ionic-angular';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Page({
    templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
    static get parameters(){
        return [[Http], [NavController], [NavParams], [Platform]];
    }
    constructor(http, nav, navParams, platform) {
        this.platform = platform;
        this.http = http;
        this.posts = null;
        this.http.get('http://promotionapp.de/json_test.php')
          .map(res => res.json())
          .subscribe(
            data => this.posts = data.data.children}, 
            error => this.cantDoRequest = "Error");
        this.nav = nav;
    }

Also interisting when clicking on another tab and clicking back to this view I see all information that should have been shown from the start.

posts is null when the template is first rendered. This line:

…does not execute during the constructor call. It executes once the XHR has returned (which is why you are seeing what you are seeing when you come back to the page). You have a bunch of options, such as using the AsyncPipe, but the simplest is probably to assign a usable dummy object to this.posts in the constructor (instead of null).

1 Like

I tried it with a dummy object and removed the http request completly and still I see the same error…

Then maybe you want to use the elvis operator or use a more elaborate dummy, because the error message is telling you that your indexOf calls are too optimistic.

1 Like

Well I tried everything… Dummies, async pipes, elvis operators, different kind of events and nothing worked. It seems the problem was that I was using an object. I transferred the object to an array and everything worked out fine. Well, learning step by step though ;D.

But still thank you very much @rapropos