[英]var in ionic template undefined, but console.log displays it
I get an undefined error from the call in the ionic template:我从离子模板中的调用中得到一个未定义的错误:
ERROR TypeError: "this.x is undefined"错误类型错误:“this.x 未定义”
But when I log this.x to the console it looks fine.但是当我将 this.x 登录到控制台时,它看起来很好。
Maybe it's an easy problem, but I just started learning this.也许这是一个简单的问题,但我刚刚开始学习这个。 If anyone can help, it would be appreciated :)如果有人可以提供帮助,将不胜感激:)
this.http.get('xy.json', {responseType: 'text'})
.subscribe(response => {
this.x = JSON.parse(response);
console.log(this.x);
});
getCurrentObj() {
return this.x[0];
}
Template: {{ getCurrentObj().text }}
模板: {{ getCurrentObj().text }}
Json:杰森:
{
"0": {
"text" : "This is sample text 1",
"type" : "xy"
}
}
this.x from console.log:来自 console.log 的 this.x:
Object(1)
0: Object { text: "This is sample text 1", type: "xy", … }
<prototype>: Object { … }
The main problem is that you are trying to render data which are not loaded yet.主要问题是您正在尝试呈现尚未加载的数据。
subscribe()
is an asynchronous function, so you have to wait for the data from there. subscribe()
是一个异步函数,所以你必须等待那里的数据。 There are two ways to do it.有两种方法可以做到。
{{ getCurrentObj().text }}
into <ng-container *ngIf="x"></ng-container>
=> <ng-container *ngIf="x">{{ getCurrentObj().text }}</ng-container>
将您的{{ getCurrentObj().text }}
包裹到<ng-container *ngIf="x"></ng-container>
=> <ng-container *ngIf="x">{{ getCurrentObj().text }}</ng-container>
get
request and then use it with the async
pipe in the template =>您可以从执行get
请求的函数返回一个 Observable,然后将它与模板中的async
管道一起使用 =>component:成分:
getCurrentObj(): Observable<CORRECT_INTERFACE_HERE> {
return this.http.get('xy.json', {responseType: 'text'});
}
template:模板:
{{ (getCurrentObj() | async)?.text }}
Another thing is that you don't need JSON.parse(response)
as the httpClient
do it for you.另一件事是你不需要JSON.parse(response)
因为httpClient
为你做。
You should display data like this你应该像这样显示数据
get getCurrentObj() {
return this.x[0];
}
Then in your template然后在你的模板中
{{getCurrentObj}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.