2017-08-31 97 views
0

這就是我如何節省1個記錄如何保存1個鍵值對中的多個記錄?

save.ts

save(){ 

     this.sectionObj = { 
          "name" : this.myname, 
          "contactno" : this.contactno 
         }; 
     localStorage.setItem("resume",JSON.stringify(this.sectionObj)); 
     } 

本地存儲的結果如下

key是恢復

value

{ 
"name":"saurabh..", 
"contactno":"892732224" 
} 

現在我想在這個鍵值中添加另一條記錄,我該如何做到這一點,以便每次保存時都會追加一條新記錄,而不僅僅是更新當前的記錄?

+0

您需要加載它,解析它,編輯它並保存回去。 加載它使用JSON.parse(localStorage.getItem('簡歷')) –

+0

好吧我得到你,請幫助我如何解析它並添加'this.sectionObj'它,保存應該類似,我相信 – user2828442

+0

Make數組並推送所有值並將其存儲在本地存儲器 – Sreemat

回答

0
add(key: string, value: string) { 
    // Read currently saved object 
    const tmp = localstorage.getItem('resume'); 
    this.sectionObj = JSON.parse(tmp); 

    // Add new key/value pair 
    this.sectionObj[key] = value; 

    // Save again 
    localStorage.setItem('resume', JSON.stringify(this.sectionObj)); 
} 
0

試試這個代碼來讀,寫和處理異常,我希望它幫全給你

setData(){ 
let tmpdata = localstorage.getItem('resume'); 
this.sectionObj = { name : this.myname, contactno : this.contactno }; 
if (tmpdata){ 
    this.tmpSectionObj = JSON.parse(tmpdata); 
    this.tmpSectionObj.push(this.sectionObj); 
    localstorage.setItem('resume',JSON.stringify(this.tmpSectionObj)); 

    }else{ 

    localstorage.setItem('resume', JSON.stringify([])); 
    } 
} 
+0

請注意sectionObj = {};不是一個數組,但dataObj = [];是,我該怎麼辦? – user2828442

+0

使用其他一些變量從本地存儲中獲取對象數組,並通過數組索引值獲取特定對象並在此指定.sectiinObj –

+1

使用您的建議代碼檢查編輯答案 –

0

你可以使用這個基本概念 - 1.獲取現有的項目中本地存儲 2.解析它,如果存在 3.推新對象 4.更新本地存儲

邏輯-

save(){ 
    dataObj = []; 
    this.sectionObj = { "name" : this.myname, 
          "contactno" : this.contactno 
         }; 

    data = localStorage.getItem('resume'); //get existing item in localstorage 
    if(data) //check if it exists or not empty 
    {  
     dataObj = JSON.parse(data); //parse string 
    } 
    dataObj.push(this.sectionObj); 
    localStorage.setItem("resume",JSON.stringify(dataObj)); 
} 
+0

像這樣 - this.data = localStorage.getItem( '恢復'); //獲取localstorage中的現有項目 if(this.data)//檢查是否存在空 this.dataObj = JSON.parse(this.data); //解析字符串 } this.dataObj.push(this.sectionObj); localStorage.setItem( 「簡歷」,JSON.stringify(this.dataObj));',它說運行時錯誤 this.dataObj.push不是一個函數 – user2828442

+0

請注意sectionObj = {};不是一個數組,但dataObj = [];是,我該怎麼辦? – user2828442

+0

您始終可以將對象推入數組中。因此,如果您的本地存儲沒有「簡歷」項,那麼您必須先創建一個空數組,然後向其中添加一個對象,然後保存在本地存儲中。在下一次調用中,您將在localstorage中擁有一個包含一個對象的數組。現在您可以將新對象推入現有數組,然後保存。希望澄清! –