Ask all your coding questions @ codequery.io

Angular services are for building out code that can be shared across multiple components. Also known as singletons, services restrict the instantiation of a class to one object. This means the same functions and properties can be shared throughout your app from a single shared instance.

Services are perfect for calling web services or storing user session data because you can share data between components without having to hit the web service each time. In this tutorial, we provide a basic angular 4 service example using the Angular CLI.

Angular 4 Service Example

We'll be using the Angular CLI to create our app. Create a new Angular project by running:

ng new angularService

This will create a new Angular project named angularService. Navigate to the root directory of your newly created project and run:

ng g service session

This will create a new session service for our Angular app. Specifically, the CLI will generate:

a session.service.ts file under the src/app directory

file under the src/app directory a session.service.spec.ts file under the src/app directory

Please note: unlike other tooling, the ng g service command won't automatically configure your root module app.module.ts to provide the service. To include the service in your app, you must import it and include it as a provider in app.module.ts.

import { BrowserModule } from '@angular/platform-browser';

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



import { AppComponent } from './app.component';

import { SessionService } from './session.service'



@NgModule({

declarations: [

AppComponent

],

imports: [

BrowserModule

],

providers: [SessionService],

bootstrap: [AppComponent]

})



export class AppModule { }

To include the service as a provider, you must first import the service via import { SessionService }. Then you must register the SessionService as a provider in the @NgModule decorator. By registering the service as a provider, you make it available everywhere in the application.

Adding properties to the SessionService

session.service.ts

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



@Injectable()



export class SessionService {

userName = "Sam"

constructor() { }

}

Angular 4 @Injectable

Now that you've got your application configured to use the SessionService, it's time to build out the service a bit. Replace yourfile with the following:

You'll notice the service is set up very similar to an Angular component. A key difference is the @Injectable decorator imported and used by Angular services. The @Injectable decorator simply provides dependency injection for the service.

Since your SessionService has no dependencies, you could omit the @Injectable decorator and everything would still work. If your service does have dependencies (such as the HttpService) then the app will crash without the @Injectable(). As best practice, you should always include the @Injectable decorator with any service you create. While your service may not depend on anything, it keeps your code consistent and accommodates future dependencies.

You'll notice the SessionService class now has a single property userName. You'll be accessing this property from your main app component.

Accessing the service from a component

Now that you have a working service with a username property, it's time to access the service from a component. Open the auto-generated app.component.ts and replace it with the following:

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

import { SessionService } from './session.service'



@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})



export class AppComponent {

currentUser;

constructor(session:SessionService){

this.currentUser = session.userName;

}

}

Notice that the SessionService is first imported so the main AppComponent can use it. Also notice how the constructor function takes the SessionService as a parameter. This demonstrates how dependency injection works with Angular 4. Dependencies are imported and included in the constructor function.

The AppComponent class now has a currentUser property. Notice how we set this to the session.userName property defined in our service.

In your corresponding app.component.html template, add the following HTML:

Hello {{currentUser}}

Now that you've referenced the currentUser property from the main AppComponent, you should be able to see the property's value displayed on the page. Run ng serve and navigate to localhost:4200 in your browser to make sure everything is working.

Conclusion

This demonstrates how to implement a very basic Angular service. Use Angular services when you want to persist a single class across multiple components. Be sure to use the @Injectable() decorator as best practice and to ensure your services can accommodate any dependency injection.