Reading list Switch to dark mode

    Communicating with Backend/Server in Angular Js

    Updated 9 February 2022

    Today we will learn how to communicate backend/server in Angular.

    We know Angular is used to develop single-page applications.

    Component which consists of An HTML template which deacres what to render on the page. So we can create pages with the help of Components in AngularJs. So now you can write HTML static pages in angular.

    Now our goal is to fetch data from the server to render dynamic data from server / database.

    AJAX enables the communication with the backend / servers without refreshing the page.
    As AngularJS also used for single page applications. it provides built in support for AJAX communication with server.

    Start your headless eCommerce
    now.
    Find out More

    Steps of communicating with Backend / Server in Angular Js –

    1. Import HTTPClientModule
    2. Create a service where we will create function send http requests to the server.
    3. Create a Component and use the service functions to Get / Add / Update / Delete data from Angular page.

    We will understand the process to communicate with server with an example.

    So we will work on a Product. We will send get / post / put / delete http requests to the server for

    • Getting Product info from database at server side (get)
    • Adding Product info to the database at server side (post)
    • Updating Product info to the database at server side (put)
    • Deleting Product from the database at server side (delete)

    Here at server side any server side language Or Framework could be there. Which will use its process to connect with database and process data to / from the database.

    So we only set the requests from the Angular and you can use any server side code for processing the requests on server side.

    Setup HTTPClientModule

    To use HTTPClientModule in our application, We will import the HTTPClientModule in your app.module.ts file.
    Import HTTPClientModule from the ‘@angular/common/http’ angular package.

    //app.module.ts
    
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        AppRoutingModule,
        BrowserModule,
        HttpClientModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

    Now we can use HTTPClientModule anywhere in our application and it is already imported in app.module.ts file.

    Here first we have imported HttpClientModule and the we imported HttpClientModule in imports array.

    Now we can use HTTPClientModule anywhere in our application and it is already imported in app.module.ts file.

    Service Interacting with server (product.service.ts)

    As mostly HTTP requests are created independent of compoments. So we will do in in a service file.

    Let’s describe the product.service.ts functions called in the product.component.ts

    Now let’s create service file where we will interact with server through HTTP requests for http methods.

    // code for product.service.ts
    
    import { Injectable } from '@angular/core';
    import { Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import { Product } from './product';
    import { HttpClient } from '@angular/http';
    
    @Injectable()
    export class ProductService {
    
        constructor(
            private http: HttpClient) { }
    
        // Create a get http request (get product information in json format)
        getProduct(id: number): Observable<Product> {
            return this.http.get(`$this.http_product_url/${id}`)
                .map((response: Response) => response.json());
        }
    
        // Create a post http request (post/add product data to server)
        addProduct(context: any) {
            return this.http.post(`$this.http_product_url`, JSON.stringify(context))
                .map((response: Response) => response.json());
        }
    
        // Create a put http request (put/update product data to server)
        updateProduct(id:number, context: any) {
            return this.http.put(`$this.http_product_url/${id}`, JSON.stringify(context))
                .map((response: Response) => response.json());
        }
    
        // Create a delete http request (delete product to server)
        deleteProduct(id: number) {
            return this.http.delete(`$this.http_product_url/${id}`)
                .map((response: Response) => response.json());
        }
    }

    So in the service we have imported HttpClient. Then we have used it in the constructor parameter with the http alias.
    After that we have used this.http for http methods calls to the server.

    Component using service methods (product.component.ts)

    Lets create the component and call service methods from component (product.component.ts)

    // code for product.component.ts
    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, Validators } from '@angular/forms';
    import { Router, ActivatedRoute, Params } from '@angular/router';
    import { ProductService } from './product.service';
    
    // Product is a model class for Products
    import { Product } from './product';
    
    @Component({
        templateUrl: 'product.component.html',
        styleUrls: ['product.component.css']
    })
    
    export class ProductComponent implements OnInit {
        id_product: number;
        productForm: any;
    
        constructor(
            private formBuilder: FormBuilder,
            private route: ActivatedRoute,
            private router: Router,
            private productService: ProductService
        ) {
            // build form fields for product
            this.productForm = this.formBuilder.group({
                'name': ['', [ Validators.required ] ],
                'reference': [''],
                'status': [1],
                'description': [],
                'units': []
            });
    
            // Get the id of the product from the url
            route.params
                // (+) converts string 'id' to a number
                .subscribe((params: Params) => this.id_product = +params['id']);
        }
    
        // In this function we will fetch the product information when page is initiated
        ngOnInit() {
            // if we are getting id of the product from the URL then we will get information of the product from the server
            if (this.id_product) {
                this.productService.getProduct(this.id_product)
                .subscribe((product: Product) => {
                    // here you will get all product information in product var
                    // do your tasks here with product information
                },
                error => {
                    // do your tasks here if error occurs while fetching data
                });
            }
        }
    
        // This function will be called when product form will be submitted
        productFormSubmit() {
            // If id_product is there in the URL then we will update the product information (PUT method)
            // Otherwise we will add the product  (POST method)
            this.id_product ? this.updateProduct() : this.addProduct();
        }
    
        // Function for adding the product (POST)
        addProduct() {
            let context = this.productForm.value;
            this.productService.addProduct(context)
                .subscribe(
                    data => {
                        if(data.success) {
                            // Do your things if product successfully added
                        } else {
                            // Do your things if product is not added
                        }
                    }, error => {
                        // Do your things if some error occurred in the request
                    });
        }
    
        // Function for updating the product (PUT)
        updateProduct() {
            let context = this.productForm.value;
            this.productService.updateProduct(this.id_product, context)
                .subscribe(
                    data => {
                        if(data.success) {
                            // Do your things if product successfully updated
                        } else {
                            // Do your things if product is not updated
                        }
                    }, error => {
                        // Do your things if some error occurred in the request
                    });
        }
    }

    In the above example you can see we have called methods from the product.service.ts file.

    We have tried to understand the process with the help of product form. So that product information can be fetched(GET), added (POST), updated (PUT) and deleted (DELETE). Lets explain http methods calls in details.

    GET method call: In ngOnInit(), we called this.productService.getProduct(this.id_product) for getting the information of the product from server of a specific id.

    productFormSubmit() is called when we submit the form created for the Product. And addProduct() or updateProduct() will be called according to the id_product availability.

    POST method call: In the addProduct() function we are posting the product form data to the server through this.productService.addProduct(context). So that we can add product information in the server side.

    PUT method call: In the updateProduct() function we are sending the product form data to the server through this.productService.updateProduct(context). So that we can update product information in the server side.

    Likewise you an use this.productService.deleteProduct(this.product) to delete the product.

    So this is how you can send requests to the server with the different http methods.

    hope this blog help you to understand the process of interacting with backend servers in Angular.

    reference: Communicating with backend services using HTTP

    Happy coding.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home