Custom Students Service

Learn how to display data on a page using services.

Before you flesh out the Roster page, you need to get some students to display. Later you will want to tie the list into a data store of some sort, but you do not need to do that just to get some data displayed on the page.

Angular services

For that, you are going to create a simple “Students” service you can inject into the pages that need it. Use the command line to create the service.

Angular CLI

In this case, it does not matter whether or not you use the Angular CLI or the Ionic CLI. Go ahead and use the Angular CLI this time. Enter the following command.

npx ng generate service Students --dry-run

In case this is your first time seeing npx, I will explain. When you install npm packages globally, as you did with the Ionic CLI, the package’s main binary will be linked to a folder that is already in your execution path.

On the other hand, the Ionic-Angular project template installs the Angular CLI as a local project dependency. This means that the entire Angular CLI is installed in your project’s node_modules folder. This makes it visible to your project’s npm scripts, but completely invisible to your system. When you type ng into your terminal, it has no idea where to find that command.

The npx command, which is installed with node and npm, knows to look for commands inside of your node_modules command. Before npx, if you wanted to run a command you had installed locally, you had two choices:

  1. Run it as an npm script, because npm already know where to look.

  2. Prepend your command with ./node_modules/{toolname}/bin.

This command is simply instructing the Angular CLI to generate a service named Students. The dry-run option gives you a chance to see what will happen, and then tweak things if you do not like what you see.

CREATE src/app/students.service.spec.ts (338 bytes)
CREATE src/app/students.service.ts (136 bytes)
NOTE: The "dryRun" flag means no changes were made.

By default, the service will be created in the app folder, but not in a folder of its own, and it will be created with a unit test. We have already run these commands for you. The service is present in the application provided below.

Inside the students.service.ts file, you will create an interface, a constant, and a function.

Implementing the service

Create a Student object as an interface. Remember, interfaces do not exist in JavaScript, and will completely vanish upon build. Their sole purpose for us is to enable parameter type checking, code completion, and intellisense inside the code editor.

Get hands-on with 1200+ tech skills courses.