Code Monkey home page Code Monkey logo

angular-httpclient-examples's Introduction

Angular 9/8/7 HttpClient Examples (GET, POST , UPDATE, DELETE)

In this how-to tutorial , we'll learn what is the HttpClient API available from HttpClientModule and how to use it in Angular 9 by example with request timeout, responsetype, query parameters, http headers, interceptors, typed and full responses, and error handling.

Also check out:

We'll be seeing examples of common HTTP methods such as GET, PUT, PATCH, POST and DELETE, that you usually need to use when communicating with a server, or consuming and fetching data from a REST API server.

We'll be learning about:

  • Accessing Http Headers,
  • Passing Http Parameters,
  • Specifying HttpClient ResponseType i.e Text, JSON or Blob,
  • Setting up HttpClient Interceptors,
  • Implementing Http Error Handling,
  • Dealing with Browser CORS and the Same Origin Policy

This tutorial is divided in the following parts:

Also read:

Angular 7|6 Tutorial: Using Angular HttpClient with Node & Express.js - Example POST Requests

Angular 7|6 By Example: HTTP GET Requests with HttpClient (Services, async pipe and Observables)

Run Fake Rest API server

npm install -g json-server
json-server --watch db.json 

Run Development server

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

angular-httpclient-examples's People

Contributors

ahnerd avatar angular-cli avatar techiediaries avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-httpclient-examples's Issues

Angular httpClient.put method not updating the data

check updateHotel() method in hotel.service.ts file and onUpdateHotel() method in hotel-edit.component.ts file. the problem is when i am trying to update a single hotel using onUpdateHotel() method i am getting error: "Missing 'hotels' id" what i am doing wrong?

hotel.service.ts file

import { Injectable } from '@angular/core';
import { HotelModel } from "./hotel.model";
import {Observable, of, Subject} from "rxjs/index";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {catchError, map, tap} from "rxjs/internal/operators";

@Injectable({
  providedIn: 'root'
})
export class HotelService {
  private hotelsUrl = 'api/hotels';  // URL to web api
  private hotels: HotelModel[] = [];
  constructor(private http: HttpClient) { }

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  getHotels():Observable<HotelModel[]>{
    return this.http.get<HotelModel[]>(this.hotelsUrl).pipe(
      catchError(this.handleError<HotelModel[]>('get hotels', []) )
    )
  }

  getHotel(id: number | string){    // or you can go 2nd method which is just below
    return this.getHotels().pipe(
      map((hotels:HotelModel[]) => hotels.find(hotel => hotel.id === +id ))
    );
  }

  updateHotelInDetailSection(hotel:HotelModel):Observable<any>{
    return this.http.put(this.hotelsUrl, hotel, this.httpOptions).pipe(
      catchError(this.handleError<any>('update hotel'))
    )
  }

  updateHotel(id:number, hotel:HotelModel):Observable<any>{
    const url = `${this.hotelsUrl}/${id}`;
    return this.http.put<HotelModel>(url, hotel, this.httpOptions).pipe(
      tap(updatedHotel => console.log('hotel updated', url)),
      catchError(this.handleError<any>('updateHotel'))
    )
  }


  private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {
    console.error(error); // log to console instead
    return of(result as T);
    };
  }

}

hotel-edit.component.ts file

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
import { HotelService} from "../hotel.service";
import {ActivatedRoute, ParamMap, Params, Router} from "@angular/router";
import { switchMap } from "rxjs/internal/operators";
import { HotelModel } from "../hotel.model";

@Component({
  selector: 'app-hotel-edit',
  templateUrl: './hotel-edit.component.html',
  styleUrls: ['./hotel-edit.component.css']
})
export class HotelEditComponent implements OnInit {
  hotelEditForm:FormGroup;
  editMode;
  id:number;
  hotel:HotelModel;
  constructor(
              private fb: FormBuilder,
              private hotelService:HotelService,
              private route:ActivatedRoute,
              private router:Router,

              ) { }

  ngOnInit() {
    this.route.params.subscribe(
      (params: Params) => {
        this.id = +params['id'];
        this.editMode = params['id'] != null;
        this.initHotelForm()
    }
    );

    this.hotelEditForm = this.fb.group({
    name:[''],
    price:[''],
    imagePath:[''],
    description:[''],
    city:[''],
    address:['']
  })
  }

  private initHotelForm(){
    let hotelName = '';
    let hotelPrice:number=null;
    let hotelImagePath = '';
    let hotelDescription = '';
    let hotelCity = '';
    let hotelAddress = '';

    if(this.editMode){
       this.hotelService.getHotel(this.id).subscribe(data => {
         const hotel = data;
         hotelName = hotel.name;
         hotelPrice = hotel.price;
         hotelImagePath = hotel.imagePath;
         hotelDescription = hotel.description;
         hotelCity = hotel.city;
         hotelAddress = hotel.address;


       this.hotelEditForm.controls['name'].setValue(hotelName);
       this.hotelEditForm.controls['imagePath'].setValue(hotelImagePath);
       this.hotelEditForm.controls['price'].setValue(hotelPrice);
       this.hotelEditForm.controls['description'].setValue(hotelDescription);
       this.hotelEditForm.controls['address'].setValue(hotelCity);
       this.hotelEditForm.controls['address'].setValue(hotelAddress);

      });
    }
  }
  onUpdateHotel(){
    if(this.editMode){
      this.hotelService.updateHotel(this.id, this.hotelEditForm.value).subscribe(()=>
        this.router.navigate(['/hotels'], { relativeTo: this.route })
      )
    }
  }

}

I got error in cmd?

D:\xampp\htdocs\fff>npm install json-serve
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"
})

D:\xampp\htdocs\fff>json-server --watch db.json
'json-server' is not recognized as an internal or external command,
operable program or batch file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.