2017-10-05 66 views
0

我遇到的問題是,我無法在JSON對象內添加/更改給定的項目。我試圖將其轉換爲使用一個簡單的put但是,這並不工作,因爲:Property "put" does not exist in type of "JSON"本地存儲中的角度更新值

Key: 123 Value:{"name":"123","email":"123","password":"123","country":"123","about":"123","image":""}  

我的方法來改變這個國家的價值。

newJson:JSON; 
onSubmit(value:any){ 

      this.newJson = JSON.parse(localStorage.getItem(this.id)); 
      this.newJson.put("country", value.country); 
      localStorage.setItem(JSON.stringify(this.newJson)); 
    } 

我從參數中得到的值(提交的值)

{"country":"Portugal"} 
+1

可以使用this.newJson.country = value.country – Niladri

+0

同意用@Niladri - 一旦你解析了'localStorage',它就是一個JS對象,你可以使用普通的點符號來訪問它的屬性 –

+0

你也可以聲明'newJson:any;' – Niladri

回答

0

嘗試這樣的:

export class Component { 
    private jsonObj: any = {}; 
    private key: string = "123"; 

    constructor(){ 
     this.jsonObj = { 
      "name": "123", 
      "email": "123", 
      "password": "123", 
      "country": "123", 
      "about": "123", 
      "image": "" 
     } 
     localStorage.setItem(this.key, JSON.stringify(this.jsonObj)); 
    } 

    ngOnInit() { 
     let localStorageJsonData = JSON.parse(localStorage.getItem(this.key)); 
     localStorageJsonData.country = "france"; 
     localStorage.setItem("obj", JSON.stringify(localStorageJsonData)); 
     console.log('localStorageJsonData', localStorageJsonData); 
    } 
}