Search code examples
angulartypescriptionic-frameworkionic2

ionViewWillEnter does not fire (ionic 2, angular 2, typescript)


I pass the correct data into this.items, but it does not appear after switching to the view, when the ionViewWillEnter method usually should fire. Instead it does after typing something into my searchbar

ionViewWillEnter method:

ionViewWillEnter() {
          ...
          this.http.post('http://www.example.com/select.php', creds, {
              headers: headers
          })
          .map(res => res.json().User) 

          .subscribe(
          data => this.data = data.map(user => user.Name), 
          err => this.logError(err),
          () => console.log('Completed')
          );


      this.items = this.data;
  }

searchbar:

getItems(ev) {
    // Reset items back to all of the items
    this.initializeItems(); // same code as ionViewWillEnter

    // set val to the value of the ev target
    var val = ev.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.items = this.items.filter((item) => {
        return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

my html:

<ion-searchbar (ionInput)="getItems($event)"> </ion-searchbar>

  <ion-list>
    <ion-item *ngFor="let item of items">
      {{ item }}
...

Solution

  • Keep in mind that Http requests (that which you are using in your ionViewWillEnter() function) are asynchronous. This means that any code outside of the request scope will continue to run while your application makes a request to the server.

    You make the assignment of this.data to this.items at the end of of the lifecycle event, but you do this outside of your Http request. Make the assignment within the data => callback, instead.