Open In App

How to use services with HTTP methods in Angular v17?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Angular 17, services play an important role in managing HTTP requests to backend servers. By encapsulating HTTP logic within services, you can maintain clean, modular, and testable code. In this article, we’ll explore how to use services to handle HTTP requests effectively in Angular 17 applications.

Services in Angular

Services in Angular are classes that combine reusable logic and functionality. They provide a way to centralize data manipulation, business logic, and integration with external APIs or services. Services are typically injected into components or other services using Angular’s dependency injection system.

Implementing services with HTTP methods

To demonstrate the implementation of each approach, let’s go through the steps to create a new Angular application and implement the different approaches one by one.

Step 1: Create a new Angular application

ng new http-demo

Folder Structure:

Screenshot-2024-04-15-115315

Updated Dependencies in package.json file

  "dependencies": {
"@angular/animations": "^17.2.0",
"@angular/common": "^17.2.0",
"@angular/compiler": "^17.2.0",
"@angular/core": "^17.2.0",
"@angular/forms": "^17.2.0",
"@angular/platform-browser": "^17.2.0",
"@angular/platform-browser-dynamic": "^17.2.0",
"@angular/platform-server": "^17.2.0",
"@angular/router": "^17.2.0",
"@angular/ssr": "^17.2.3",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Step 2: Import required Modules

Since we’ll be working with HTTP requests, we need to install to import modules related to HttpClient package, which provides the HttpClient’s functionalities. inside app.component.ts add below code

//app.component.ts

@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, JsonPipe, CommonModule, HttpClientModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})

Approach 1: Using the HttpClient service directly in your component

This approach involves injecting the HttpClient service into your component and making HTTP requests directly from the component’s methods. While this approach works, it is generally not recommended as it violates the separation of concerns principle and makes the component harder to test and maintain.

Code Example:

JavaScript
// src/app/app.component.ts

import { CommonModule, JsonPipe } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, JsonPipe, CommonModule, HttpClientModule],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    data: any;

    constructor(private http: HttpClient) {
        this.getData();
    }

    getData() {
        this.http.get('https://jsonplaceholder.typicode.com/posts/1')
            .subscribe(
                response => {
                    this.data = response;
                    console.log(response);
                },
                error => {
                    console.error('Error fetching data:', error);
                }
            );
    }
}

Approach 2: Creating a dedicated service for HTTP requests

This is the recommended approach. You create a separate service dedicated to making HTTP requests, and then inject this service into the components that need to communicate with the server. This approach promotes code reusability, testability, and separation of concerns.

Step 1: Generate a new service using the Angular CLI:

ng generate service data

Code Example:

JavaScript
// src/app/data.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

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

    constructor(private http: HttpClient) { }

    getData(): Observable<any> {
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
    }
}
JavaScript
// src/app/app.component.ts

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    data: any;

    constructor(private dataService: DataService) { }

    fetchData() {
        this.dataService.getData()
            .subscribe(
                response => {
                    this.data = response;
                    console.log(response);
                },
                error => {
                    console.error('Error fetching data:', error);
                }
            );
    }
}

Output:

using angular services with http methods



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads