Angular HTTP with Observable & Model

In my last article i discuss on the how to use for RxJs Observable. In these article we create model for Observable. Model is nothing but Creating Custom Data type.


Let’s create Product data type in below example.


/**
* ./app/model/product.ts *
*/
export class ProductModel {
    constructor(
        public id: number, 
        public name: string, 
        public price: string,
        public image: string,
        public description: string
        ){}
}

In service when we get Data products we expect result with above defined filed.




getProducts() : Observable<ProductModel[]> {

         return this.http.get(this.url).map((res:Response) => res.json())
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

     }

Using the map operator, we need call the .json method for the response because response is not a collection of data but It’s JSON String.
In Angular 4.3+ version default data response now JSON so we can skip these line.
Lest create Post method for creating Product.



//Add Product
addProduct (data: Object): Observable<ProductModel[]> {
        let bodyString  = JSON.stringify(data); // stringfy the content
        let headers     = new Headers({ 'Content-Type': 'application/json' }); // Set content type to JSON
        let options     = new RequestOptions({ headers: headers }); // Create a request option

        return this.http.post(this.url, body, options) 
                         .map((res:Response) => res.json()) 
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
    }   



When using GET, POST we have return data of observer so in component we need to subscribe that data for getting result from their. In below example how to subscribe data of services.


/**
* Need to import model & services that we created.
*/
import { Component, Input, Output} from '@angular/core';
import { ProductModel } from '../model/product'
import { ProductService } from '../services/product.service';

@Component({
    selector: 'product-list',
    template: 'products.html'
})

export class ProductListComponent { 
    
     constructor(
        private productser: ProductService
        ){}

    getProductsList(){
    
     this.productser.getProducts().subscribe( productdata => {
                                    console.log(productdata);
                                }, 
                                err => {
                                    console.log(err);
                                });
      }


    }
}


Spread the love
  • 20
  •  
  •  
  •  
  •  
  •  
  •  
  •