Angular 4 Display JSON Data from HTTP Get Request

前端 未结 2 1583
萌比男神i
萌比男神i 2021-02-06 02:01

I have a simple Angular 4 application which is contacting a HTTP REST server and this server is simply returning a JSON payload and I would like to display this JSON payload as

2条回答
  •  青春惊慌失措
    2021-02-06 02:22

    You have two options:

    • Use the built-in pipe JsonPipe (this.data should be of type any):

      Data Obtained is: {{ data | json }}

    • Get the JSON string manually:

      this.data = JSON.stringify(res.json()); //data is a string :)

      or

      Data Obtained is: {{ JSON.stringify(data) }}

    You have to understand that any value in a template is shown via calling its .toString() method, so a basic object (something like {key: value}) just shows [object Object]

    Here you have a working demo, check the app.ts file, the ajax call and the template with the json pipe is there.

提交回复
热议问题