【发布时间】:2018-10-04 02:41:11
【问题描述】:
我是 Angular 新手,我正在开发 Angular 6 / Spring Boot 2 项目。我有这个 TypeScript 类:
export class Partner {
constructor
(
public id: number,
public name: string,
public email: string,
public phone: string,
public address: string,
public picture: string,
public latitude: number,
public longitude: number,
public horary: string,
public comment: string,
public specialOffer: boolean,
public offer: string,
public location: Location,
public tripAdvisorLink: string,
public type: Type,
public country: string,
public hotWords: HotWord[],
) {}
}
所以,例如我想创建一个合作伙伴,我需要选择一个Location。
在我的 HTML 中,我有:
<div class="form-group">
<label for="partner_location" class="form-control-label" required>Choose location <span class="text-danger">*</span></label>
<select id="partner_location" class="form-control" [(ngModel)]="partner.location" name="partner_location">
<option *ngFor="let location of locations" [value]="location">{{location.name}}</option>
</select>
</div>
在我的创建伙伴组件中:
export class CreatePartnerComponent implements OnInit {
partner = new Partner(undefined, '', '', '', '', '', undefined, undefined, '', '', false, '', null, '', null, '', null);
types: Type[];
locations: Location[];
message = '';
error = '';
constructor(
private getPartnersService: GetPartnersService,
private getTypesService: GetTypesService,
private getLocationService: GetLocationsService
) {}
ngOnInit() {
this.loadInitialData();
}
loadInitialData() {
this.getLocationService.getLocations().subscribe(locations => this.locations = locations);
this.getTypesService.getTypes().subscribe(types => this.types = types);
}
onSubmit() {
console.log('Partner = ' + JSON.stringify(this.partner));
this.getPartnersService.createPartner(this.partner)
.subscribe(partner => {
if (partner.id !== undefined) {
this.showMessage();
window.scrollTo(0, 0);
} else {
this.showError();
window.scrollTo(0, 0);
}
});
}
这是我的创建伙伴方法:
const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}) };
createPartner(partner: Partner): Observable<Partner> {
const url = `${baseUrl}/partner/add`;
return this.http.post<Partner>(url, partner, httpOptions)
.pipe(catchError(HandleError.handleError<Partner>('createPartner')));
}
我在 Spring 中遇到一个错误,说他无法从 [Object object] 创建 Location。我的console.log('Partner = ' + JSON.stringify(this.partner)); 方法打印:
Partner = {"name":"Test production","email":"v.solodoukhin@outlook.com","phone":"32489836733","address":"brolekestraat","picture":"","latitude":"55","longitude":"1.23424324","horary":"9 - 18 every day","comment":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaa","specialOffer":true,"offer":"5%","location":"[object Object]","tripAdvisorLink":"http://brol.be","type":"[object Object]","country":"Belgium","hotWords":null}
据我了解,http post请求发送location : [object Object]....
如何做到这一点?
【问题讨论】:
-
你能给我们提供你的
ControllerJava 类吗? -
你的问题在于选项值绑定。它应该是
[ngValue]="location"而不是[value]="location"。见stackblitz.com/edit/angular-pckh2b
标签: angular typescript