Search⌘ K
AI Features

Angular Services

Explore how to build Angular services that utilize HttpClient to make HTTP GET requests. Understand service provision in the root module, dependency injection, and the use of observables with TypeScript interfaces to handle asynchronous data in a reactive way.

Angular services

In the newly-created photos.service.ts file. The Angular CLI has generated the outline of a service:

TypeScript 3.3.4
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PhotosService {
constructor() { }
}

🙋‍♂️ Joe asks: What Does providedIn Mean?

An Angular app can be made up of any number of modules. These modules can be split up and dynamically loaded on the frontend as needed. Angular needs to know which module we want our service to be under. Providing a service in root means that the entire application can access a single, shared instance of this service (and is the default option).

Bringing in the HttpClient

The first order of business is to bring in HttpClient.

There are two steps for injecting anything in Angular.

  1. The first is to import the class from the Angular library itself. This import is used for type hinting as well as informing Angular what needs to be injected:
import { HttpClient } from '@angular/common/http';

⚠️ ...