我有一项服务,我正在尝试更新记录,这只是对组件数据的更改造成不利。
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
}
);
}
我该如何解决这个问题?关于问题可能是什么想法?
答案 0 :(得分:2)
请使用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)