Skip to content
ashwanth kumar Reddy edited this page Sep 25, 2023 · 4 revisions

What is a service ?? Use of it

Angular services are singleton objects ,services are a fundamental building block of the framework that encapsulate common functionality A component should use services for tasks that don't involve the view or application logic. Services are good for tasks such as fetching data from the server, validating user input, or logging directly to the console. By defining such processing tasks in an injectable service class, you make those tasks available to any component

ng generate service [name]


AngularJS vs Angular version of Services


For the purpose of the undestanding i have taken a example of kommonitor Elememt visibilty helper service

Kommonitor Element Visiblity Helper Service

service responsible for managing the visibility of elements in a web application. It is designed to handle the visibility of various UI elements or controls based on certain conditions, roles, and The service also checks whether the user is authenticated. If the user is authenticated and has specific roles, certain UI elements are made visible
AngularJS Service

In AngularJS, services are typically defined using the angular.module method, and dependencies are specified within an array as strings
angular.module('kommonitorElementVisibilityHelper', ['kommonitorDataExchange', 'kommonitorKeycloakHelper']);
angular
  .module('kommonitorElementVisibilityHelper', [])
  .service(
    'kommonitorElementVisibilityHelperService', ['$rootScope', '$timeout', '$http', '$httpParamSerializerJQLike', '__env', 
    'ControlsConfigService', 'Auth', 'kommonitorDataExchangeService', 'kommonitorKeycloakHelperService',
    function ($rootScope, $timeout,
      $http, $httpParamSerializerJQLike, __env, ControlsConfigService, Auth, kommonitorDataExchangeService, kommonitorKeycloakHelperService) {
      // Service logic here
    }]);
Angular Service

In Angular, services are defined using the @Injectable decorator, and dependencies are injected directly into the service's constructor. The providedIn, 'root' option in the decorator indicates that this service is a singleton
import { Injectable, Inject } from '@angular/core';
import { environment } from 'env_backup';
import { ajskommonitorDataExchangeServiceeProvider, ajskommonitorKeycloackHelperServiceProvider } from 'app-upgraded-providers';
import { kommonitorDataExchangeService } from 'util/genericServices/kommonitorDataExchangeService/kommonitor-data-exchange-service.module';
import { kommonitorKeycloackHelperService } from 'util/genericServices/kommonitorKeycloakHelperService/kommonitor-keycloak-helper-service.module';
import { KommonitorConfigStorageService } from '../kommonitorConfigStorageService/kommonitor-config-storage-service.service';

@Injectable({
  providedIn: 'root'
})
export class KommonitorElementVisibilityHelperService {
  // Service logic here
}

Dependency Injection


In AngularJS, dependency injection is done by specifying dependencies as strings in an array and then injecting them into the service function parameters ![dependency injection](https://angular.io/generated/images/guide/architecture/dependency-injection.png)
angular
  .module('kommonitorElementVisibilityHelper', [])
  .service(
    'kommonitorElementVisibilityHelperService', ['$rootScope', '$timeout', '$http', '$httpParamSerializerJQLike', '__env', 
    'ControlsConfigService', 'Auth', 'kommonitorDataExchangeService', 'kommonitorKeycloakHelperService',
    function ($rootScope, $timeout,
      $http, $httpParamSerializerJQLike, __env, ControlsConfigService, Auth, kommonitorDataExchangeService, kommonitorKeycloakHelperService) {
      // Service logic here
    }]);

In Angular, dependency injection is more straightforward and uses TypeScript and decorators.

import { Injectable, Inject } from '@angular/core';
import { environment } from 'env_backup';
import { ajskommonitorDataExchangeServiceeProvider, ajskommonitorKeycloackHelperServiceProvider } from 'app-upgraded-providers';
import { kommonitorDataExchangeService } from 'util/genericServices/kommonitorDataExchangeService/kommonitor-data-exchange-service.module';
import { kommonitorKeycloackHelperService } from 'util/genericServices/kommonitorKeycloakHelperService/kommonitor-keycloak-helper-service.module';
import { KommonitorConfigStorageService } from '../kommonitorConfigStorageService/kommonitor-config-storage-service.service';

@Injectable({
  providedIn: 'root'
})
export class KommonitorElementVisibilityHelperService {

constructor(@Inject(KommonitorConfigStorageService) private controlsConfigService: KommonitorConfigStorageService, 
            @Inject(ajskommonitorKeycloackHelperServiceProvider) private authService: kommonitorKeycloackHelperService, 
            @Inject(ajskommonitorDataExchangeServiceeProvider) private kommonitorDataExchangeService:kommonitorDataExchangeService,private )
{ }
}

Admin View

These code snippets determine if the user has an "admin" role. If the user has admin privileges, certain UI elements are made visible. This is a common pattern for giving administrators access to additional features.

// Check if user is in admin role AngularJS version
if(Auth.keycloak.showAdminView){
  return true;
}

// Check if user is in admin role Angular version
if (this.authService.showAdminView()) {
  return true;
}

Event Broadcasting:

Both AngularJS and Angular snippets demonstrate event broadcasting. Events are broadcasted to notify other parts of the application that something significant has occurred, often triggering actions or updates in response.

// Broadcast an event in AngularJS
$rootScope.$broadcast("changeIndicatorDate");
// Broadcast an event in Angular
this.eventService.changeIndicatorDate();

Observable Patterns

The Angular snippet illustrates the use of RxJS Observables for handling asynchronous operations. Observables are used to fetch and process data asynchronously, making it easier to manage complex asynchronous code flows. AngularJS doesnt make use of observables

// Use RxJS Observables for asynchronous operations
this.controlsConfigService.getControlsConfig().pipe(
  map(config => config.filter(element => element.id === id)[0])
).subscribe(element => {
  // Handle asynchronous operations
});

Role-Based Visibility

In both AngularJS and Angular, these snippets check if a user has a role that allows them to see a specific element on the UI. If the user's roles match the required role for the element, it returns true, indicating visibility
AngularJS

// Check if user has allowed role for a specific element
var hasAllowedRole = false;          
for (var i = 0; i < element.roles.length; i++) {
  if(Auth.keycloak.tokenParsed.realm_access.roles.includes(element.roles[i])){
    return true;
  }	
}

Angular

// Check if user has allowed role for a specific element using RxJS
this.controlsConfigService.getControlsConfig().pipe(
  map(config => config.filter(element => element.id === id)[0])
).subscribe(element => {
  if (element.roles === undefined || element.roles.length === 0) {
    return true;
  } else if (this.authService.isAuthenticated() && element.roles.includes(this.advancedModeRoleName)) {
    return true;
  } // ...
});

Injecting a Service into a Component in Angular

In AngularJS, services are injected into a component using the $inject property or the array notation.

// AngularJS Component
angular.module('myApp')
  .component('myComponent', {
    templateUrl: 'kommonitor-diagrams.template.html',
    controller: ['$scope', 'kommonitorDataExchangeService', function ($scope, kommonitorDataExchangeService) {
      // Use myService here
    }]
  });

In Angular, services are injected into a component in two ways constructor Injection or by making use of @Inject Decorator.

By Constructor Injection

In Angular, you simply specify the service as a constructor parameter, and Angular's dependency injection system handles the rest
// Angular Component
import { Component } from '@angular/core';
import { kommonitorDataExchangeService } from 'util/genericServices/kommonitorDataExchangeService/kommonitor-data-exchange-service.module';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
})
export class MyComponent {
  constructor(private kommonitorDataExchangeService:kommonitorDataExchangeService) {
    // Use myService here
  }
}
By using @Inject Decorator

In Angular, the @Inject decorator can be used to specify a token when multiple providers with the same type are available.
import { Component, Inject } from '@angular/core';
import { kommonitorDataExchangeService } from 'util/genericServices/kommonitorDataExchangeService/kommonitor-data-exchange-service.module';
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
})
export class MyComponent {
  constructor(@Inject(kommonitorDataExchangeService) private kommonitorDataExchangeService: any) {
 
  }
}