【问题标题】:How to get variables from JSON string in Ionic 4 template?如何从 Ionic 4 模板中的 JSON 字符串中获取变量?
【发布时间】:2018-10-23 04:18:52
【问题描述】:

我在我的数据库列之一中保存了一个 JSON 字符串。现在,在检索它时,我打印了一个完整的字符串,但打印了特定的变量。

下面是模板

    <!-- The card -->
    <ion-card *ngFor="let comment of feed[0].meta.comments">
       <div *ngIf="comment.comment_by" class="card-title"></div>
      <div class="card-subtitle">{{comment}}</div> 
    </ion-card>
    <!-- The card End-->

这里 {{comment} 给出以下输出

"{"comment_by_id":"4","comment_by":"Elizabeth","comment":"The Comment","comment_date":"02-05-2018 09:37:03pm"}"

但是 {{comment.comment_by_id}} 不会打印任何内容。 如何获取通过 JSON 字符串访问的数据?

JSON 响应供参考:

【问题讨论】:

  • 你把JSON字符串解析成JSON了吗?
  • 另外,您使用的是哪个版本的angular?我认为你没有使用HttpClient
  • @NanditaAroraSharma 我很不确定如何解析模板内的 JSON 字符串。 JSON.parse() 给出无法读取未定义的属性“解析”
  • @ShashankVivek 感谢您的回复。是的,我肯定在使用 HttpClient
  • 你能分享你的http代码吗? HttpClient 提供默认的 json 转换 :( 。你能像 angular2 一样尝试.json() 一次吗。stackoverflow.com/questions/40136352/…

标签: json angular ionic-framework ionic3


【解决方案1】:

响应对象的类型有问题。我相信您在使用httpClient get 方法时没有定义响应类型。

this.http.get<NoTypeDefinedHere>(this.myUrl);

因此返回的对象似乎是无类型的匿名对象。

快速解决方案

尝试访问以下格式的特定变量

comment[comment_by_id]

理想的解决方案

通过 typescript interface 定义返回的 json 响应的类型。 并在http get 方法中引用它。

this.http.get<MyDefinedInterface>(this.myUrl);

DO ALSO CHECK - 未进行传递对象时意外错误处理响应。

【讨论】:

    【解决方案2】:

    您能否在您正在呼叫的服务中尝试这样的事情

    return this.http.get<JSONObject>(API_URL)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 2011-05-28
      相关资源
      最近更新 更多