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 >
<div >
<div >
<div >
<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.
Thank You
CodePudding user response:
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;
});
}
}
CodePudding user response:
You can use async pipe and get rid of subscribing inside component. Because async pipe will auto unsubscribe when component destroyed.
export class ListComponent implements OnInit {
response$:Observable<IStudentList[]>;
constructor( private studentAPI: StudentAPIService ) { }
ngOnInit(): void {
this.response$ = this.studentAPI.studentList();
}
}
Now You can iterate response$ like below..
<div >
<div >
<div >
<div >
<table id="student_Table">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of response$ | async">
<td>{{ row.student_name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
See above <tr *ngFor="let row of response$ | async">
this is auto-subscribe and you will get your list data in html and iterate over it and display it.