Angular中findIndex返回-1问题:Trending/Popular电影数据匹配失败
问题排查与解决方案
可能的原因及对应解决方法
1. JSON数据结构不一致
检查trending-movies.json和popular-movies.json的结构是否与theatre-movies.json完全一致:
- 若Theatres的JSON是直接的数组格式:
而另外两个JSON是嵌套结构(比如数据包裹在某个字段中):[{"id": "1", "title": "示例电影"}, ...]
此时{"moviesList": [{"id": "1", "title": "示例电影"}, ...]}this.movies接收的不是数组,findIndex自然无法匹配到数据。解决方法是根据实际结构调整赋值:// 假设嵌套字段为moviesList,需根据实际JSON修改 this.movies = movies.moviesList;
2. ID类型不匹配
路由参数id默认是字符串类型,但如果trending-movies.json/popular-movies.json里的id是数字类型,隐式转换可能导致匹配失败。建议统一类型后用严格相等判断:
let index = this.movies.findIndex( (movie: { id: number | string }) => String(movie.id) === this.id );
或者直接对齐类型:
// 若JSON里的id是数字,将路由参数转为数字 this.id = Number(this.route.snapshot.params['id']);
3. 路由参数大小写不匹配
确认路由传递的type参数大小写是否与代码判断一致。比如路由传trending(全小写),但代码判断的是'Trending',会导致url未正确赋值。可以统一大小写后再判断:
this.type = this.route.snapshot.params['type'].trim(); const normalizedType = this.type.charAt(0).toUpperCase() + this.type.slice(1).toLowerCase(); if (normalizedType === 'Trending') { this.url = 'http://localhost:4200/assets/data/trending-movies.json'; } // 其余判断同理修改
调试辅助建议
在getMovie中添加日志,直观确认数据状态:
this.http.get(this.url).subscribe((movies) => { console.log('接口返回原始数据:', movies); // 确认是否为数组、结构是否正确 console.log('当前路由ID:', this.id); // 确认ID参数是否正确获取 this.movies = movies; let index = this.movies.findIndex( (movie: { id: string }) => movie.id == this.id ); console.log('匹配到的索引:', index); if (index > -1) { this.movie = this.movies[index]; } });
内容的提问来源于stack exchange,提问作者Elbry 74
相关产品推荐
相关产品推荐

