简体   繁体   中英

How do I return JSON data as a table in my template.html file in angular

I am a total web developer noob and somehow I have been assigned to writing some angular to produce these reports even though I have no idea what I'm doing (basically my employer wants to see if they can avoid making a new hire if they can avoid it). Here is my component.ts file:

import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
  styleUrls: ["./styles.scss"],
  templateUrl: "./template.html"
})
export class MyRouteData {
  MyDataObject: object;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .get("http://localhost:54499/MyRoute/GetMyData")
      .subscribe(response => {
        console.log(response);
        this.MyDataObject = response;
      });
  }
}

Where the GetMyData endpoint basically runs the following query:

Select Top 20 CustomerId, FirstName, LastName, Address, PhoneNumber, Created From Customers Order by Created Desc

I can return the data to the page as a JSON with the following template.html file:

<div style="background-color: white; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12); padding: 16px 8px 0 8px">
    <table>
        <tr>
            <td>{{MyDataObject|json}}</td>
        </tr>
    </table>
</div>

How do I return the data to the screen in a table?

I've made a few attempts and doing some loops but with no success.

You need to use ngFor :

HTML

    <div style="background-color: white; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12); padding: 16px 8px 0 8px">
        <table>
         <thead>
           give the table head columns
         </thead>
            <tr *ngFor="let data of MyDataObject">
                <td>{{data.name}}</td>
                <td>{{data.value}}</td>
            </tr>
        </table>
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM