Angular Service

Angular Services are used to include backend API in the Angular Project. you can create service through CLI command.
Syntax:-

ng g s serviceName

Example:- Suppose you have to create user service.

ng g s user

When the above command is run then generated two files.

1) user.service.ts
2) user.service.spec.ts

1) user.service.ts:- In this file you can include get method API, post method API, put method API, delete method API and patch method API.

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

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

  constructor() { }

// post method API
   
userLogin(postData):Observable<any>{
return this.http.post<any>('http://abc.com'+'/login',{'email':postData.userEmail,'password':postData.userPassword})
.pipe(
   catchError(this.handleError)
  )

}

// get method API

userList():Observable<any>{
return this.http.get<any>('http://abc.com'+'/user-list')
.pipe(
   catchError(this.handleError)
  )

}

Note:- userLogin() and userList() methods have http://abc.com as a backend API domain.

In user.component.ts file:- Now you have to include userLogin and userList Service methods.

import { Component,ChangeDetectionStrategy,OnInit,ChangeDetectorRef } from '@angular/core';
import { FormGroup,FormBuilder, Validators } from '@angular/forms';
import { UserService } from './user.service';
import { Router,ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

 userlogin: FormGroup;
  user_submitted:boolean=false;
  userData:any=[];
  constructor(private fb: FormBuilder,
    private router:Router,
    public UserService:UserService
 
    ) { }
 
 
 ngOnInit() {  
 
       this.userlogin = this.fb.group({
           email: ['', [Validators.required]],
           password: ['', [Validators.required]],
      });
    }
 
 
// convenience getter for easy access to form fields
get userdata() { return this.userlogin.controls; }
 
 
 loginSubmit(){  
     this.user_submitted = true;
	    console.log(userlogin);  
	    if (this.userlogin.invalid) {
	     //  show validation
	       return;
	   }


   return this.UserService.userLogin(this.userlogin.value).subscribe((res) => {
 
     if(res.status == 200){
       
        this.router.navigateByUrl('/user-list');
       
  
      }else{
  
         console.log(res.message);
         return;
  
      }
  });

}

// user list

 userList(){  
  
  return this.UserService.userList().subscribe((res) => {
 
     if(res.status == 200){
       
        this.userData=res.data;
       
  
      }else{
  
         console.log(res.message);
         return;
  
      }
  });

}


 
  } 

Note:- providedIn:’root’ is following the singletern service pattern so this service can be used any component of the application.

2) user.service.spec.ts:- this file is used to test the user service.

import { TestBed } from '@angular/core/testing';

import { UserService } from './admin.service';

describe('UserService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: UserService = TestBed.get(UserService);
    expect(service).toBeTruthy();
  });
});