Friday, June 16, 2023

Services

 API Services


How to Generate Service file :

      In the command line ng generate service API_Service.

Import HTTP Client module

import { HttpClientModule } from '@angular/common/http';

Import Httpclient in the Service file

import { HttpClient } from '@angular/common/http';
      
API.Service:


 Constructor( public http:Httpclient ){}

let url = "https://jsonplaceholder.typicode.com/posts";

getdata(){
return this.http.get(url);
}


app.componet.ts file


import {API} from '/api.service';

Constructor( public api:API ){}

ngOninit(){
this.api.getdata().subscribe(data =>{
console.log(data);
})
}

Another method to Call API Service file:

  
 this.options = {
            headers: new HttpHeaders({
                Accept: 'application/json',
                Authorization: 'Bearer ' + localStorage.getItem('access_token'),
            })
        };


getData(url: any) {

        let apiUrl = this.baseUrl + url;
        return this.http.get(apiUrl, this.options).pipe(map(res => res));
    }

Another method to call

 getData(){

        return this.http.get('https://jsonplaceholder.typicode.com/guide/');
    }

App.component.ts

 getStates(value: any) {
    var url = '/GetState/' + value
    this.apiService.getData(url).subscribe((Object: any) => {
      this.stateslist = Object.data;

    }, (err) => {
      if (err.error.message == "Unauthenticated.") {
      }
      else {
        console.log(err);
      }
    })
  }

App.component.ts:

 getclientlist() {
    this.loader = true;
    var url = 'GetCompany' + '/' + this.routerId();
    this.ApiService.getData(url).subscribe((Object: any) => {
      this.loader = false;
      this.List = Object.data;
      this.List.forEach(ele => {
        ele.index = this.List.indexOf(ele) + 1;
        ele.name = ele.firstname + ' ' + ele.lastname
      });

    }, (err) => {
      this.loader = false;
      if (err.error.message == "Unauthenticated.") {
        this.openError = true;
      }
      else {
        console.log(err);
      }
    })
  }
Post Method:

Constructor( public http:Httpclient ){}

let url = "https://jsonplaceholder.typicode.com/posts";

postdata(formData:any){
  return this.http.post(url,formData);
    }





how to call api in angular

                            Api Call in service file Making API calls is a common task in Angular applications, and it can be achieved using...