Top

Services


With a website this big, we sometimes need to use same variable globally and also we need them to be reactive which means that we that variable is changed then that changes should reflect wherever that variable is used.

Implementation of Services.:

We have created a separate folder to manage all services. You can find all the services at the below given folder:

src > app > shared > services

Creating Services

Open the terminal and navigate to the services folder folder and run the below given code

ng generate service service_name

Executing this command will create a file with name service-name.service.ts. It will contain below given code

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

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

  constructor() { }
}

This variable is now available globally. You can use them by importing and defining an instance of it in the constructor of the component where you are going to use it. An example is shown below.

export class ServiceNameService {
  public variable1: boolean = false;

  constructor() { }
}

Using Services in the components.

This variable is now available globally. You can use them by importing and defining an instance of it in the constructor of the component where you are going to use it. An example is shown below.

import { Component, OnInit, Inject } from '@angular/core';
import { NavService } from '../../services/nav.service';

@Component({
  selector: 'some-component',
  imports: []
  templateUrl: './some-component.component.html',
  styleUrls: ['./some-component.component.scss']
})

export class SomeComponent implements OnInit {
  
  constructor(public layout: LayoutService,
  public service_nameServices: serviceNameService) {}
  
  someFunction(){
      this.service_nameServices.variable1 = true 
  }
}

And that's the basic about using the services. For more information please refer This Guide.

Warning: Make sure that you provide an instance of the service in the constructor of the component, and make use of that instance to access everything inside that service.