Services in AngularJS

Services are essentially containers for business logic that our components shouldn’t request directly. Services contain other built-in or external services such as $http, that we can then inject into component controllers elsewhere in our app. We have two ways of doing services, using .service() or .factory(). With ES2015 Class, we should only use .service(), complete with dependency injection annotation using $inject.

Classes for Service

Here’s an example implementation for our <todo> app using ES2015 Class:

/* —– todo/todo.service.js —– */

export class TodoService {

constructor($http) {

‘ngInject’;

this.$http = $http;

}

getTodos() {

return this.$http.get(‘/api/todos’).then(response => response.data);

}

}

/* —– todo/todo.module.js —– */

import angular from ‘angular’;

import { TodoComponent } from ‘./todo.component’;

import { TodoService } from ‘./todo.service’;

import ‘./todo.scss’;

export const TodoModule = angular

.module(‘todo’, [])

.component(‘todo’, TodoComponent)

.service(‘TodoService’, TodoService)

.name;

Get industry recognized certification – Contact us

Menu