angular - Angular/Ionic Storage,如何动态存储数据
问题描述
所以我有一些代码允许用户选择联系人并将数据解析为数组。但是,问题是无法永久存储该数据,因为用户离开组件时,数据就会消失。
我一直在尝试使用 Ionic 存储来存储该数据,但我缺乏如何正确执行此操作的知识。
这是相关的代码。
export class ContactComponentComponent implements OnInit {
constructor(private contacts: Contacts, private storage: Storage) {
this.getContact();
}
mContacts = [
{
id: [0],
name: '',
number: ''
},
{
id: [1],
name : [''],
number: ['']
},
{
id: [2],
name : [''],
number: ['']
},
{
id: [3],
name : [''],
number: ['']
},
{
id: [4],
name : [''],
number: ['']
}
];
ngOnInit() {}
pickContact(contactId) {
this.contacts.pickContact().then((contact) => {
this.mContacts[contactId].name = contact.name.givenName;
this.mContacts[contactId].number = contact.phoneNumbers[0].value;
this.storage.set('contact-name', JSON.stringify(this.mContacts.name));
this.storage.set('contact-number', JSON.stringify(this.mContacts.number));
});
}
getContact()
{
this.storage.get('contact-name').then((val) => {
console.log('Contact Name: ', val);
});
this.storage.get('contact-number').then((val) => {
console.log('Contact Number:', val);
});
}
}
这是HTML
<ion-list>
<ion-grid>
<ion-row>
<ion-col>
<ion-item-group *ngFor="let contacts of mContacts">
<ion-card (click) = "pickContact(contacts.id)">
<ion-item lines = "none">
<ion-label class="ion-text-wrap">Name: {{contacts.name}}</ion-label>
</ion-item>
<ion-item lines = "none" >
<ion-label class="ion-text-wrap">Number: {{contacts.number}}</ion-label>
</ion-item>
</ion-card>
</ion-item-group>
</ion-col>
</ion-row>
</ion-grid>
</ion-list>
我知道这是糟糕的代码,但我不知道如何在用户选择并检索它之后保存这个数组,当组件被调用时
解决方案
我终于找到了答案,希望这对某人有所帮助。
constructor(private contacts: Contacts, private storage: Storage) {
this.getContact();
}
key:string = "contacts";
mContacts = [
{
id: [0],
name: '',
number: ''
},
{
id: [1],
name : [''],
number: ['']
},
{
id: [2],
name : [''],
number: ['']
},
{
id: [3],
name : [''],
number: ['']
},
{
id: [4],
name : [''],
number: ['']
}
];
ngOnInit() {}
pickContact(contactId) {
this.contacts.pickContact().then((contact) => {
this.mContacts[contactId].name = contact.name.givenName;
this.mContacts[contactId].number = contact.phoneNumbers[0].value;
this.saveContacts();
});
}
saveContacts(){
this.storage.set(this.key, JSON.stringify(this.mContacts));
}
getContact()
{
this.storage.get(this.key).then((val) => {
console.log('Contact Name: ', val);
if (val != null && val !== undefined) {
this.mContacts = JSON.parse(val);
}
});
}
}
推荐阅读
- c# - 用户控件 Windows 窗体中的简单注入器属性注入
- python - 在python中模拟类的属性的属性
- python - 在Python中查找字符串中多次出现的单词
- json - 如何使用角度 11 将多个标题行添加到 ag 网格中
- r - 如何只删除连续的重复行?
- ios - 由于无法完成操作,应用程序崩溃。(KCLErrorDomain 错误 1。)
- oracle - 从 RobotFramework DatabaseLibrary 执行 PLSQL 脚本文件抛出错误
- javascript - 条纹元素基于什么?他们如何保护它?
- python - Pyinstaller,只打包部分使用的第三方包,其余在另一台PC上调用
- powershell - Get-Content 无法从变量中读取