Angular6 HTTP Request

HTTPRequest is the most commun use task in Angular6. Today i will show you how to use Angular HTTPRequest to fetch data from server or API. In real world project we will not use static data we have to use server or api then the role of HTTPRequest comes in play.
Demo

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { AppRoutingModule,routingComponents } from './app-routing.module';
import { RecordsService } from './records.service'
@NgModule({
  declarations: [
    AppComponent,
   routingComponents
  ],
  imports: [
    BrowserModule,HttpClientModule,AppRoutingModule
  ],
  providers: [RecordsService],
  bootstrap: [AppComponent]
})
export class AppModule { }
records.service.ts


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

@Injectable()
export class RecordsService {

  constructor(private _httpClient:HttpClient) { }
	public url:string = "http://nitesh-thapa.com/angular6-http-request/assets/data.json";
  getResult(){
    return this._httpClient.get(this.url)
		
  }
}
Consuming service by component employelist.component.ts
import { Component, OnInit } from '@angular/core';
import { RecordsService } from '../records.service'
interface myObj {
  obj:Object;
}
@Component({
  selector: 'app-employeelist',
  templateUrl: './employeelist.component.html',
  styleUrls: ['./employeelist.component.css']
})
export class EmployeelistComponent implements OnInit {

  results:Object = []
  constructor(private serviceData: RecordsService) { }

  ngOnInit() {
  this.serviceData.getResult().subscribe(data =>{
		  this.results = data;
		})
  }

}

Consuming service by component departmentlist.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap} from '@angular/router';
import { RecordsService } from '../records.service'

@Component({
  selector: 'app-departmentlist',
  templateUrl: './departmentlist.component.html',
  styleUrls: ['./departmentlist.component.css']
})
export class DepartmentlistComponent implements OnInit {
 results:Object = []
  constructor(private serviceData: RecordsService) { }

  ngOnInit() {
    this.serviceData.getResult().subscribe(data =>{
		  this.results = data;
		})
  }

}
data.json
[
      {
		"color": "red",
		"value": "#f00"
	},
	{
		"color": "green",
		"value": "#0f0"
	},
	{
		"color": "blue",
		"value": "#00f"
	},
	{
		"color": "cyan",
		"value": "#0ff"
	},
	{
		"color": "magenta",
		"value": "#f0f"
	},
	{
		"color": "yellow",
		"value": "#ff0"
	},
	{
		"color": "black",
		"value": "#000"
	}
    ]

Leave a Reply

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