2017-01-16 63 views
0

我是NoSQL世界的新手,因爲默認情況下Ionic 2支持簡單的鍵值數據庫,所以我在這裏給了一些幫助。Ionic 2存儲 - 添加記錄

我的應用程序有一個非常大的形式。我如何着手保存新記錄?我如何檢索這些特定的記錄?

目前,保存一個新的記錄,我做這樣的事情:

save(data){ 
    let newData = JSON.stringify(data); 
    this.storage.set('reports', newData); 
} 

的問題,這是它覆蓋,而不是插入新記錄備案。

我檢索的記錄是這樣的:

getData() { 
    return this.storage.get('reports'); 
} 

怎樣去獲取在存儲的JSON使用某些值的特定記錄?

謝謝。

回答

4

您需要做的是將報告設置爲數組並將其設置爲存儲。 每次你需要插入一個新的記錄,做一個

function(newData){ 
    var some_variable = storage.get('reports'); //get Existing Table 
    some_variable.push(newData); //Inserts the new record to array 
    storage.set('reports', some_variable); //Saves report with updated data 
} 

對於單獨獲得特定的報告,我希望你有一些ID或獨特的屬性,Y,它可以區分的報告。假設你有如下的報告JSON:

var report {id : "UniqueID", name : "A sample report json"} 

然後拿到報告,

function(reportId){ 
    var reports = this.storage.get('reports');//fetches your reports Array 
    var wantedReport = {};//Variable to store the wanted report 
    reports.forEach(function(r){ //Looping the array.You can use a forloop as well 
     if(r.id === reportId){ //filtering for the wanted reportId 
      wantedReport = r; // storing the report to variable 
     } 
    }) 
    return wantedReport; //Returning the report to the caller. 
} 

或者,如果你使用SQL和要存儲這些數據,那麼你的類似SQL的方式可以安裝Sqlite cordova plugin並將您的數據存儲在Sqlite數據庫中。

+0

非常好,謝謝。根據我的關係數據庫背景,我更喜歡使用SQL,但Ionic 2不再支持WebSQL,這已被棄用,很快就不會被瀏覽器支持。雖然我最終將部署iOS,但我仍想堅持使用@ ionic/storage,這是跨平臺的,但需要您去NoSQL。 – Muhammad

+0

只有在瀏覽器中測試時,Ionic纔會默認使用webSql。如果您已經安裝了Sqlite cordova插件,那麼當您在移動設備上運行它時,會在您的應用中獲得一個實際的Sqlite數據存儲區..但我猜想離子/存儲非常簡單和容易一旦你通過NoSql學習曲線學習。 :-) –

+0

你可以看看這個嗎? http://stackoverflow.com/questions/41689516/ionic-2-and-json-data-addition 謝謝。 – Muhammad