angular
angular

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
   |   app.component.css
   |   app.component.html
   |   app.component.spec.ts
   |   app.component.ts
   |   app.module.ts
   |   
   |---user
           user.service.spec.ts
           user.service.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.

app/user/user.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class UserService {

  constructor() { }

}

References:
https://angular.io/guide/styleguide#service-names

Last modified: November 21, 2017

Author