Working with services

In Angular, it is a common practice to use a service to interact with a REST API or with other resources, such as the localStorage API. The class below defines a service named MovieService, which can be used to send HTTP requests to the backend Node.js application.

A service is just a class, and it doesn't require any special decorators. However, the following code snippet uses the @Injectable decorator because it is going to be injected into the MovieComponent. We will learn more about dependency injection later, in the Dependency injection in Angular section.

The following methods perform some HTTP requests to the server using the Fetch API. There is a method to fetch all movies from the movies REST API:

import { Injectable ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.