Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show data to angular?

list.component.ts

import { Component, OnInit } from '@angular/core';
import { StudentAPIService } from 'src/app/services/student-api.service';
import { Student } from 'src/app/model/student';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {

  constructor( private studentAPI: StudentAPIService ) { }

  ngOnInit(): void {

    this.studentAPI.studentList().subscribe(res=>{
      console.log(res);
      return res;
    });

  }

}

list.component.html

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="center">
        <table id="student_Table">
          <thead>
            <tr>
              <th>Name</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let row of res">
                <td>{{ row.student_name }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

I am new in angular and I want to show data in list.component.html table. In ts file I have successfully fetch data through an API and data are showing in console.log(res) but unable to show in table. So, How can I do this? Please help me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank You

>Solution :

You have to define the variable (and it should be public) in the class definition, then assign the service response to that variable. So;

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {

  constructor( private studentAPI: StudentAPIService ) { }

  public res: any | any[]; // you can create an interface to the data type

  ngOnInit(): void {

    this.studentAPI.studentList().subscribe(res=>{
      this.res = res;
    });

  }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading