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.
We'll cover the following...
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:
Below is a summary of the above code:
We start by importing CourseService in line 2.
- Next, we create a variable called
coursesin line 10. - In line 12, we inject the
course serviceinside theconstructor. - In line 18 we create a function called
fetchCourses(). Inside thefetchCourses()function in line 19 we instantiatecourseServiceand call thegetCourses()method that holds the logic for gettingcoursesfrom our database. We proceed to subscribe to the data returned from thegetCourses()method. - Next, in line 21, we reference the
coursesvariable we created earlier in line 10 and append the data from our REST API to thecoursesvariable. - In the event of an error, we make provision for that in line 24 by creating an error handler.
Step 2: Displaying fetched data in the template
Here, we display the data fetched from the database in the template. We need to loop through the data using the *ngFor directive. We can see how this is implemented in the code below:
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}
Below is a summary of the code in the widget above:
- To display the data from the database in the table, we use the
*ngFordirective inside thetrtag in line 20. The*ngFordirective allows us to repeat a section of the HTML template from a collection by looping through the data. Within the*ngFordirective, we create a variable calledcoursethat holds the data from thecoursesvariable we created in thecourse-list.component.tsfile. - Next in line 21, we display the
namefield in our database through interpolation. - In line 23, we use conditional styling using the
[ngStyle]attribute to state that if the course status from the database is set tocomplete, the test color should begreen. On the other hand, if the course status is set topending, the text color should bered. - Next, in line 24, line 27, and line 30, we display the data retrieved from the database through interpolation.
We can test the steps we’ve implemented so far by compiling the code widget, creating a new course on the dashboard, and seeing if it displays on the Course List page.