Search⌘ K

Fetching Courses Created from the Database

Explore how to fetch courses stored in a database and display them in your Angular app by consuming REST APIs. Understand how to use Angular's *ngFor directive to loop through data and apply conditional styling based on course status.

In this lesson, we’ll display all the courses created and saved into the database on the client-side of our application. To do that, we need to take the following steps:

Step 1: Consuming the REST API

To consume the REST API to show a list of created courses, we head to the course-list directory and open the course-list.component.ts file. Next, we integrate the code below:

TypeScript 3.3.4
import { Component, OnInit } from '@angular/core';
import { CourseService } from 'src/app/services/course.service';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css'],
})
export class CourseListComponent implements OnInit {
courses: any;
constructor(private courseService: CourseService) {}
ngOnInit() {
this.fetchCourses();
}
fetchCourses() {
this.courseService.getCourses().subscribe(
(data) => {
this.courses = data;
console.log(this.courses);
},
(error) => {
console.log(error);
}
);
}
}

Below is a summary of the above code: We start by importing CourseService in line 2.

  1. Next, we create a variable called courses in line 10
...