2016-05-06 6 views
0

ionic2でsqliteデータベースを使いたいです。TypeScriptの項目スコープ(JavaScript)

次のコードでデータベースに接続し、アイテムデータを正常に取得できました。 しかし、私はthis.items配列にプッシュしていない可能性があります。

エラーは言う:

未定義のオブジェクトではありません( 'this.items' を評価)

誰もが問題が何であるかを知っていますか? 私はそれが可変範囲だと思いますが、わかりません。

import {Page, Platform} from 'ionic-angular'; 
declare var sqlitePlugin:any; 
declare var plugins:any; 

@Page({ 
    templateUrl: 'build/pages/getting-started/getting-started.html' 
}) 
export class GettingStartedPage { 
    items: Array<{title: string}>; 
    constructor(platform: Platform) { 
    platform.ready().then(()=>{ 
     this.getData(); 
    }); 
    } 

    getData(){ 
    sqlitePlugin.openDatabase({name: 'encrypted.db', key: 'Password', location: 'default'}, function(db) { 
     db.transaction(function(tx) { 
      var query: string = "SELECT * FROM items"; 
      this.items = []; <-- error happens at this row. 
      tx.executeSql(query, [], function(tx, resultSet) { 
      //alert("name: " + resultSet.rows.item(0).name); 
      this.items.push({ 
       title: resultSet.rows.item(0).name 
      });    
      }, function(error) { 
      alert('SELECT error: ' + error.message); 
      console.log('SELECT error: ' + error.message); 
      }); 
     }, function(error) { 
      alert('transaction error: ' + error.message); 
      console.log('transaction error: ' + error.message); 
     }, function() { 
      console.log('transaction ok'); 
     }); 
     }, function(error){ 
     alert('error' + error.message); 
    }); 
    } 
} 

答えて

3

利用() =>代わりのarrow functionsfunction()

これは、代わりにクラスに現在のポインティング機能を保持します。

import {Page, Platform} from 'ionic-angular'; 
declare var sqlitePlugin:any; 
declare var plugins:any; 

@Page({ 
    templateUrl: 'build/pages/getting-started/getting-started.html' 
}) 
export class GettingStartedPage { 
    items: Array<{title: string}>; 
    constructor(platform: Platform) { 
    platform.ready().then(()=>{ 
     this.getData(); 
    }); 
    } 

    getData(){ 
    sqlitePlugin.openDatabase({name: 'encrypted.db', key: 'Password', location: 'default'}, (db) => { 
     db.transaction((tx) => { 
      var query: string = "SELECT * FROM items"; 
      this.items = []; <-- error happens at this row. 
      tx.executeSql(query, [], (tx, resultSet) => { 
      //alert("name: " + resultSet.rows.item(0).name); 
      this.items.push({ 
       title: resultSet.rows.item(0).name 
      });    
      }, (error) => { 
      alert('SELECT error: ' + error.message); 
      console.log('SELECT error: ' + error.message); 
      }); 
     }, (error) => { 
      alert('transaction error: ' + error.message); 
      console.log('transaction error: ' + error.message); 
     },() => { 
      console.log('transaction ok'); 
     }); 
     }, (error) =>{ 
     alert('error' + error.message); 
    }); 
    } 
} 
+0

ありがとうございました! – tomo

関連する問題