Madogiwa Blog

主に技術系の学習メモに使っていきます。

Ionic:スワイプでページ更新する方法のメモ

Ionicで下スワイプでページ更新を行う方法をメモφ(..)

↓実装イメージはこんな感じです。

f:id:madogiwa0124:20171112232529g:plain

手順

概要

Ionicでスワイプでページ更新を実装するには、ion-refresherを使用します。
Viewのion-content内にion-refresherを配置し、(ionRefresh)="doRefresh($event)"のように実行メソッドを定義します。

詳細は下記を参照頂ければ!※Ionicの公式ドキュメントです

Refresher - Ionic API Documentation - Ionic Framework

Viewへの配置

下記のようにView内のion-content配下にion-refresherを配置します。

<ion-content no-padding>
  <ion-refresher (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>
</ion-content>

更新処理の実行及び完了の実装

Viewへの配置が終わったら.ts側にページ更新及び完了の処理を実装していきます。
下記の実装では、API呼び出しによるデータ取得の完了または、3秒経過したら完了とし、ローディングを終了させています。

@IonicPage()
  
@Component({
  selector: 'page-page-index',
  templateUrl: 'page-index.html',
})
export class PageIndexPage {
  pages = [];
  result = '';
  api_url = 'https://moook.herokuapp.com/pages.json';
  refresher = null;

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: Http, public loadingCtrl: LoadingController) {
    // ロード画面を表示
    this.presentLoading();
    // APIからデータを取得
    this.get_pages_data();
  }

  doRefresh(refresher) {
    this.refresher = refresher;
    // APIからデータを取得
    this.get_pages_data();
    // タイムアウトの設定
    setTimeout(() => {
      // ページ更新を完了とし、処理を中断
      refresher.complete();
    }, 3000);
  }

  get_pages_data(){
    this.http.get(this.api_url).subscribe(
      respons => {
        let result = respons.text();
        this.pages = [];
        JSON.parse(result || null).forEach(data => {
          this.pages.push(new Page(data)); 
        });
        if (this.refresher != null) {
          // データ取得が終わったら完了
          this.refresher.complete();
        }
      },
      error => {
        let result = 'faild : '+ error.statusText;
        console.log(result);
      }
    );
  }

}

完全なソースコードは下記に配置してありますφ(..)

github.com

以上です。