2017-04-03 61 views
0

我一直使用離子2存在的問題之一是存儲服務。我已成功設置和檢索存儲的數據。但是,當我存儲的東西,除非我刷新頁面/應用程序,其他頁面無法訪問。與離子2存儲服務同步訪問存儲

例一:編輯聯繫人

我推到一個編輯聯繫人頁面,進行更改,然後saveEdits。 saveEdits成功更改爲正確的聯繫人,但無法更新聯繫人列表直到應用程序刷新。

HTML:

<button (click)="saveEdits(newName, newPostCode)"ion-button round>Save Edits</button> 

打字稿:

saveEdits(newName, newPostCode){ 
    console.log("saveid"+this.id); 
    this.name = newName; //saves property 
    this.postcode = newPostCode; //saves property 
    this.items[this.id] = {"id": this.id, "Name": newName, "PostCode": newPostCode}; 
    this.storage.set('myStore',this.items); 
    //this.navCtrl.pop(ContactPage); 
    } 

例二:瀏覽其他網頁

上的聯繫人另一頁我通過接觸迭代,並在無線電警告框列表中顯示。同樣,聯繫人顯示成功,但是當我在添加聯繫人頁面上添加聯繫人時,新聯繫人不會出現在收音機警告框列表中。

addDests(){ 
    console.log('adddests'); 
    { 
    let alert = this.alertCtrl.create(); 
    alert.setTitle('Choose Friend'); 

    for(let i = 0; i<this.items.length; i++){ 
     console.log('hello'); 
     alert.addInput({ 
     type: 'radio', 
     label: this.items[i].Name, 
     value: this.items[i].PostCode, 
     checked: false 
    }); 
    } 



    alert.addButton('Cancel'); 
    alert.addButton({ 
     text: 'OK', 
     handler: data => { 
     console.log(data); 
     } 
    }); 
    alert.present(); 
    } 
    } 

回答

1

你改變變量指向的參考:

this.items[this.id] = {"id": this.id, "Name": newName, "PostCode": newPostCode}; 

我承擔您的LIST是否正在對由this.items引用的數組進行迭代(ngFor)?如果是,則直接更新this.items[this.id]的屬性,而不是重新初始化它。

this.items[this.id].Name = newName; 
this.items[this.id].PostCode = newPostCode; 

(順便說一句,我建議你要與你的財產的命名是一致的:無論是標識和名稱,或ID和姓名(大寫字母問題)!)。

如果對正在使用的對象的引用沒有改變,那麼將始終刷新您的「列表」視圖。唯一的例外是在給第三方庫的回調中進行的更新。在這種情況下,您可以使用NgZone來「強制」Angular將更新考慮在內。

另外,看看亞歷山大關於Observable的偉大建議。

+0

你能查看我對其他回覆的評論嗎? – Dansmith12

1

您應該使用角提供商(S)與觀察特性來通知用戶(其它頁&組件)有關的變化。

例如閱讀這篇文章:http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/

上有這個有很多的信息:https://www.google.com/search?q=angular+provider+observable

+0

有一個問題,我能夠使用以下代碼來控制正確的數據:var contacts = obs.subscribe((data)=> { console.log(data); });那麼我如何訪問這些數據?我試着把它分配給一個變量,如上所示,但它返回一個訂閱者JSON文件 – Dansmith12

+0

我也試着調用一個函數並將數據作爲參數傳遞,但它總是返回undefined – Dansmith12

+0

您只能訪問'可觀察的監聽功能(「監聽」)。您可以直接在此函數中進行更新,也可以將新的最新數據傳遞給專用於UI更新的函數(例如)。 – VinceOPS