json - 在 Angular => 错误中显示数据列表时出现此错误:TypeError:无法读取未定义的属性“0”
问题描述
我是 Angular 的新手,我有一个错误需要修复。这是我在尝试显示来自 jsonplaceholder 的数据列表时遇到的错误。我不知道代码中有什么问题。我可以寻求帮助吗?谢谢你。
错误类型错误:无法在 SafeSubscriber._next (recipe-detail .component.ts:26) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber .next (Subscriber.js:134) 在 Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77) 在 Subscriber.push../node_modules/rxjs/_esm5 /internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at BehaviorSubject.push../node_modules/rxjs/_esm5/internal/BehaviorSubject.js.BehaviorSubject._subscribe (BehaviorSubject.js:22) at BehaviorSubject.push ../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43) at BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject._trySubscribe (Subject. js:89) 在 BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29)
配方详细信息.component.ts
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id = +params['id'];
this.recipe = this.recipeService.getRecipe(this.id);
}
);
}
食谱.service.ts
@Injectable()
export class RecipeService {
recipesChanged = new Subject<Recipe[]>();
private url = "https://jsonplaceholder.typicode.com/users/";
private recipes: Recipe[];
constructor(private slService: ShoppingListService, private http: Http) {}
getRecipes() {
return this.http.get(this.url).pipe(map(res => res.json()));
}
getRecipe(index: number) {
return this.recipes[index];
}
配方-detail.component.html
<div class="row">
<div class="col-xs-12" *ngFor="let recipe of recipes">
<h1 class="list-group-item-heading">{{ recipe.id }}</h1>
<h4 class="list-group-item-heading">{{ recipe.name }}</h4>
<h4 class="list-group-item-heading">{{ recipe.username }}</h4>
<h4 class="list-group-item-heading">{{ recipe.email }}</h4>
<h4 class="list-group-item-heading">{{ recipe.phone }}</h4>
</div>
</div>
解决方案
可能是配方为空/未定义。因此,当您调用 getRecipe(0) 时会出现此错误。尝试将您的方法更改为以下内容:
getRecipe(index: number) {
if (!!this.recipes && this.recipes.length > index) {
return this.recipes[index];
} else {
return 0; //Whatever
}
}
推荐阅读
- javascript - 如何验证表单然后发出一个 post http 请求 jQuery
- rest - 获取 Yammer 消息
- asp.net - 如何使用基于令牌的授权从 Web api 下载文件
- docker - gcloud docker push 导致“拒绝:项目 'gcp-project-id-example' 的令牌交换失败。”
- python - 无法在 python 中导入 Azure 的包 NetworkSecurityGroupsOperations
- node.js - 'Error: Cyclic dependency detected' occurs when I add unique identifier to my module
- iframe - UWP 应用程序中的 PDF iframe
- c# - Word VSTO 插件:写入 Word 状态栏
- jquery - 如何在函数中获取结果作为 jquery 插件的参数
- rspec - Rails 在 rspec 测试中提供 ActiveStorage 图像