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.

To solve this problem we use services in Angular.

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 {

}

Now we can define a variable inside class serviceNameService and these variables can be accessed anywhere in the theme by importing them. Example of defining a variable inside serviceNameService is given below:

export class ServiceNameService {

  public variable1: boolean = false;
                  
}

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/navservices.service';
import { DOCUMENT } from '@angular/common';

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

export class Some implements OnInit {

  constructor(public layout: LayoutService,
    public service_nameServices: serciveNameService, 
    @Inject(DOCUMENT) private document: any
  ) {
  }

  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.