首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 6-方法总是返回-1

Angular 6-方法总是返回-1
EN

Stack Overflow用户
提问于 2018-06-04 02:26:41
回答 1查看 47关注 0票数 -2

我有一个服务,我正在尝试更新一条记录,这只是将更改添加到组件的数据中。

listData保存所有数据。

所有变量都包含数据。

例如: 1,1,my title, text

result正在成功返回到服务中。但是在我

代码语言:javascript
复制
update(id, userId, title, body) {
    this.apiService.updateById(id, userId, title, body).subscribe(
      result => {
        console.log(result);

        // PROBLEM STARTS HERE
        const currentItemIndex = this.listData.findIndex((item: {id: number}) => item.id === id);

        console.log(`CurrentIndex is: ${currentItemIndex}`); // Returns -1

        // THIS IS NEVER REACHED
        if (currentItemIndex > -1) {
            this.listData.splice(currentItemIndex, 0, {userId: userId, title: title, body: body});
        }

      },
      error => {
      console.log('There was an error: ', error); // No errors returned
    }
  );

}

我该如何解决这个问题呢?你知道问题出在哪里吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-04 02:38:14

请按照以下方式使用findIndex:

代码语言:javascript
复制
this.listData.findIndex((item) => item.id === id);

我认为对于findIndex来说,显示item的类型是不正确的

代码语言:javascript
复制
let listData = [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }]
  
  // say id was 2
  
  let id = 2;
  
  let foundIndex = listData.findIndex((eachData) => {
    // === when its and integer, is it in your case?? 
    // if not then try with ==
    return eachData.id === id;
  });
  
  console.log(foundIndex)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50669638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档