1. Angular CLI provides a command i.e.ng generate service [name] to generate Angular Service.

In src\app run following command

ng generate service user\user

After the command is executed, a new directory i.e. user is created together with 2 files under it.

   |   app.component.css
   |   app.component.html
   |   app.component.spec.ts
   |   app.component.ts
   |   app.module.ts

The 2 files are as followings:
user.service.spec.ts is for unit testing.
user.service.ts is the actual Angular Service file.
Angular recommends to give .service suffix in the name.

2. To make a class to be an Angular service:

  1. Import Injectable from Angular Core.
  2. Annotate the class with @Injectable()

Open up the Angular CLI generated user.service.ts, and you will find that Angular CLI has done the above-mentioned jobs for you.

import { Injectable } from '@angular/core';

export class UserService {

  constructor() { }



Last modified: November 21, 2017