Jeet Tupe
Jeet Tupe

Reputation: 25

How to get variables from JSON string in Ionic 4 template?

I have saved a JSON string in one of my database columns. Now while retrieving it I am getting a whole string printed but the specific variable.

Following is the Template

    <!-- 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-->

Here {{comment} gives the following output

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

but {{comment.comment_by_id}} will print nothing. How can I get the data accessed through the JSON string?

JSON Response for reference:

enter image description here

Upvotes: 0

Views: 1477

Answers (2)

abhay tripathi
abhay tripathi

Reputation: 4022

There is something wrong with the type of response object.I believe you are not defining response type while using httpClient get method.

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

therefore the returned object seems to be anonymous Object of no type.

Quick Solution

Try to access specific variable in following format

comment[comment_by_id]

Ideal Solution

Define the type of your returned json response through typescript interface. and refer it in http get method.

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

DO ALSO CHECK- unintentional mishandling of response while pass object is not made.

Upvotes: 0

Nandita Sharma
Nandita Sharma

Reputation: 13407

Can you please try something like this in your service where you are maing the call

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

Upvotes: 1

Related Questions