【问题标题】:Can't get row by id from array in localstorage无法从本地存储中的数组中按 id 获取行
【发布时间】:2021-05-22 15:43:21
【问题描述】:

我的本​​地存储中有一系列项目,如下所示:

[ {id: 1, name: "test1"}, {id: 2, name: "test2"}, {id: 3, name: "test3"}]

当我尝试在我的数组中按名称选择一行时,一切都很顺利,但如果我使用 id,则日志返回 "无法读取未定义的属性 'id'"

TS

getContacts() {
    var storedContacts = JSON.parse(localStorage.getItem('contacts'));
    console.log(storedContacts );
    this.tabContacts = storedContacts ;
   }


 getContact(id) {
        //returns -1 when I use the id
        var i = this.tabContacts
          .map(function (x) {
            return x.id;
          })
          .indexOf(id);
      
        this.tabContacts.find((x) => x.id == this.tabContacts[i].id);
  }

HTML

           <tr
            *ngFor="let contact of tabContacts"
            (click)="getContact(contact.id)"
            id="tr-{{ contact.id }}"
          >
            <td>{{ contact.name }}</td>
          </tr>

【问题讨论】:

  • 您能告诉我您是如何获取本地存储数据的吗?
  • @Shafkhan 我编辑了代码

标签: angular local-storage


【解决方案1】:

看来问题出在这里:

   <tr
      (click)="getContact(contact.name)"
            ...

当有人点击 &lt;tr&gt; 并从数组中过滤 id 时,您正在传递名称。

你应该这样做:

html:

   <tr
    *ngFor="let contact of tabContacts"
    (click)="getContact(contact.name)"
    id="tr-{{ contact.id }}"
  >
    <td>{{ contact.name }}</td>
  </tr>

TS:

  getContact(key) {
  
        var i = this.tabContacts
          .map(function (x) {
            // change this based on the field you pass from html 
            return x.id; // or x.name
          })
          .indexOf(key);
      
        .... rest of the code            
  }

P.S : 你的逻辑不是很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2017-01-30
    相关资源
    最近更新 更多