Angular 6 - метод всегда возвращает -1 - PullRequest
0 голосов
/ 03 июня 2018

У меня есть служба, и я пытаюсь обновить запись, и это просто несправедливо по отношению к изменениям в данных компонента.

listData содержит все данные.

Все переменные содержат данные.

Пример: 1, 1, мой заголовок, текст сообщения

результат успешно возвращается в службу.Но после того как я

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
    }
  );

}

Как я могу это исправить?Есть идеи, в чем может быть проблема?

1 Ответ

0 голосов
/ 03 июня 2018

Пожалуйста, используйте findIndex как:

this.listData.findIndex((item) => item.id === id);

Я не думаю, что показ типа item является правильным аргументом для findIndex

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...