gpt4 book ai didi

javascript - 无法获取 View 中的对象属性

转载 作者:行者123 更新时间:2023-12-03 05:07:02 25 4
gpt4 key购买 nike

我在 html View 中显示对象详细信息时遇到问题(使用 ionic2)。下面输出 cart.ts 文件中的正确值(输出胡萝卜)。

this.cart = resultsFromAPI     
console.log(this.cart.vegetable);

但是,当我尝试在 View 中输出它时,它不会再让我查看该页面。我假设是因为一个错误。

<h2>{{cart.vegetable}}</h2>

如果我只输出对象,我会在标题中得到 [object Object]

<h2>{{cart}}</h2>

看起来错误是“无法读取未定义的属性‘vegetable’”。如何在 ts 中读取它而不是 View ?

下面是完整的ts代码

 cart:any;

ngOnInit(){
this.getPosts(this.category, this.limit);
}

getPosts(category, limit){
this.cartService.getPosts(category, limit).subscribe(response => {
this.cart = response.data.children;
console.log( this.cart.vegetable);
});
}

答案:我按照下面的帖子操作,但必须将返回值放在调用之前

public getPosts$(category, limit) {
return this.cartService.getPosts(category, limit).map(response => {
this.cart = response.data.children;
};
}

最佳答案

这是因为您正在执行异步 API 调用,因此您应该在使用之前检查它是否可用。此外,您可以通过async管道直接将API响应用作Observable。

<h2>{{(cart | async)?.vegetable}}</h2>

对于OP编辑:您可以只写(fname 末尾的 $ 表示它是一个流):

public getPosts$(category, limit) {
return this.cartService.getPosts(category, limit).map(response => {
return response && response.data && response.data.children;
};
}

和:

ngOnInit() {
this.getPosts$(this.category, this.limit).subscribe(cart => {
this.cart = cart;
}
}

和:

<h2 *ngIf="cart>{{cart.vegetable}}</h2>

关于javascript - 无法获取 View 中的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com