techiediaries / angular-httpclient-examples Goto Github PK
View Code? Open in Web Editor NEWAngular 6/7/8/9 HttpClient CRUD Examples
Angular 6/7/8/9 HttpClient CRUD Examples
'productsObservable',products,location,families,transaction all are declared but its value is never read error thrown
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.
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 })
)
}
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.