Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.
This repository was archived by the owner on Feb 26, 2024. It is now read-only.

Angular httpClient.put method not updating the data #247

Description

@rahul6612

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 })
      )
    }
  }

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions