使用 ionic 2 存储服务同步访问存储



我在使用Ionic 2时遇到的一个反复出现的问题就是它的存储服务。我已经成功设置和检索了存储的数据。但是,当我存储某些内容时,除非我刷新页面/应用程序,否则在其他页面上无法访问它。

示例一:编辑联系人

我推送到编辑联系人页面,进行更改,然后保存编辑。 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();
  }
  }

您正在更改变量指向的引用:

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

我假设您的 LIST 正在迭代 (ngFor( this.items 引用的数组?如果是,请直接更新this.items[this.id]的属性,而不是重新初始化它。

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

(顺便说一下,我建议与您的属性命名保持一致:要么是 ID 和 Name,要么是 id 和名称(大写字母很重要!

如果不更改对正在使用的对象的引用,则"列表"视图将始终刷新。唯一的例外是在对第三方库的回调中进行的更新。在这种情况下,您可以使用NgZone来"强制"Angular考虑更新。

另外,看看亚历山大关于可观察的好建议。

您应该使用具有 Observable 属性的 Angular 提供程序来通知订阅者(其他页面和组件(有关更改的信息。

例如,请阅读这篇文章: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

最新更新