【发布时间】:2022-01-11 09:25:10
【问题描述】:
我是 Angular 的新手。我想创建一个以下列方式接受用户输入的表单。 。 为此,我创建了一个包含以下变量的类
export class Hotels {
name: string;
email: string;
address1: string;
address2: string;
bookingList: Contract[];
}
Contract 是另一个具有各自属性的模型类。
export class Contract {
start_date: string;
end_date: string;
}
前端 HTML 表单如下所示,
<form (ngSubmit) = "saveHotel()">
<input type="text" name = "name" [(ngModel)]=" hotel.name" placeholder="Enter hotel name"/>
<input type="text" name = "email" [(ngModel)]=" hotel.email" placeholder="Enter hotel email"/>
<input type="text" name = "address1" [(ngModel)]=" hotel.address1" placeholder="Enter hotel address line 1"/>
<input type="text" name = "address2" [(ngModel)]=" hotel.address2" placeholder="Enter hotel address line 2"/>
<input type="text" name = "address2" [(ngModel)]=" hotel.bookingList.start_date" placeholder="Enter hotel address line 2"/>
<input type="text" name = "address2" [(ngModel)]=" hotel.bookingList.end_date" placeholder="Enter hotel address line 2"/>
<button type="submit">Add Hotel</button>
</form>
组件文件
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hotels } from 'src/app/models/hotels';
import { HotelsService } from 'src/app/services/hotels.service';
@Component({
selector: 'app-add-hotels',
templateUrl: './add-hotels.component.html',
styleUrls: ['./add-hotels.component.css']
})
export class AddHotelsComponent implements OnInit {
hotel : Hotels = new Hotels();
constructor(private _hotelService : HotelsService,
private _router:Router) { }
ngOnInit(): void {
}
saveHotel(){
this._hotelService.saveHotels(this.hotel).subscribe(
data =>{
console.log('response', data)
this._router.navigateByUrl("/hotels");//to navigate back to main hotels pahge
}
)
}
}
服务文件
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Hotels } from '../models/hotels';
@Injectable({
providedIn: 'root'
})
export class HotelsService {
//to store http endpoint
private getUrl: string = "http://localhost:8080/get/hotels";
private postUrl: string = "http://localhost:8080/savehotel";
constructor(private _httpClient:HttpClient) { }
getHotels(): Observable<Hotels[]>{
return this._httpClient.get<Hotels[]>(this.getUrl).pipe(
map(response => response)
)
}
saveHotels(hotels: Hotels): Observable<Hotels> {
return this._httpClient.post<Hotels>(this.postUrl, hotels);//no need to map as we just have to return the posted value back to component
}
}
【问题讨论】:
-
您的 bookingList 是一个数组,而不是一个对象。所以你不能这样做:
hotel.bookingList.end_date。解决方案可能是您可以先循环您的 bookingList 的let booking of bookingList,然后您可以访问它,例如:booking.end_date。