Я получаю эти ошибки, и я не уверен, как это исправить.Я делаю форму, которая будет отправлять запрос к API.
ОШИБКА TypeError: Невозможно прочитать свойство 'email' с неопределенным значением
ОШИБКА TypeError: Невозможно прочитать свойство 'paymentMethod' с неопределенным
Я ожидаю:
createdBy: string from email input,
paymentMethod: string from paymentMethod select input,
Но я получаю:
createdBy: null,
paymentMethod: null
Интерфейсы
export interface BillingForm {
fullName: string;
email: string;
address: string;
city: string;
paymentMethod: string;
}
export interface Order {
id?: number;
companyId: number;
created: string;
createdBy: string;
paymentMethod: string;
totalPrice: number;
status: number;
orderRows: OrderRows[];
}
service.ts
public postOrder(order: Order): Observable<Order> {
console.log(order);
return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
catchError(this.handleError('postOrder', order))
);
component.ts
ngOnInit() {
this.shippingForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', Validators.required],
address: ['', Validators.required],
paymentMethod: ['', Validators.required],
city: ['', Validators.required],
})
}
onSubmit(billingForm: BillingForm) {
const order = this.newOrder(billingForm);
this.productService.postOrder(order).subscribe (
response => console.log('success', response),
error => console.log('error', error)
)
this.submitted = true;
if(this.shippingForm.invalid) {
return;
}
this.success = true;
}
newOrder(billingForm: BillingForm ): Order {
return {
companyId: 6,
created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
createdBy: billingForm.email,
paymentMethod: billingForm.paymentMethod,
totalPrice: this.totalPrice,
status: 0,
orderRows: this.orderRows
}
}
get email() {
return this.shippingForm.get("email") as FormControl;
}
get paymentMethod() {
return this.shippingForm.get("paymentMethod") as FormControl;
}
component.html
<form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">
<h5 *ngIf="success">Your form is valid!</h5>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">
<div *ngIf="submitted && shippingForm.controls.email.errors" class="error">
<div *ngIf="shippingForm.controls.email.errors.required">Your email is required!</div>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label for="payment">Payment Method: </label>
<select type="select" formControlName="paymentMethod" class="form-control" id="payment"
aria-placeholder="Mastercard">
<option selected> Choose...</option>
<option *ngFor="let paymentMethod of paymentMethods">
{{ paymentMethod }}
</option>
</select>
<div *ngIf="submitted && shippingForm.controls.paymentMethod.errors" class="error">
<div *ngIf="shippingForm.controls.paymentMethod.errors.required">Your preferred payment method is required!</div>
</div>
</div>
</form>