значение формы не добавляется в базу данных - PullRequest
0 голосов
/ 04 января 2019

введите описание изображения здесь

Я использую angular для вставки нового объекта клиента, вызывая API Java, но объект клиента не вставлен. Объект клиента, отправленный из формы, не вставлен в базу данных. однако метод getCustomers () работает. Данные формы загружаются в метод addCustomer (customer: Customer) файла data.service.ts, но не добавляются в базу данных.

1. CustomerController.java

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders ="*" )
public class CustomerResource {
@Autowired
private CustomerServiceImpl customerServiceImpl;

@PostMapping("/customers")
public Customer addCustomer(@RequestBody Customer customer){
    return customerServiceImpl.addCustomer(customer);
}  

2.Create-customer.component.html

Создать форму клиента

<form>
<div class="form-group">
  <label for="firstName">First Name</label> <input type="text"
                                                   class="form-control" 
id="firstName" required

[(ngModel)]="customer.firstName" name="firstName">
</div>

<div class="form-group">
  <label for="lastname">Last Name</label> <input type="text"
                                                 class="form-control" 
id="lastname" required

[(ngModel)]="customer.lastName" name="lastname">
</div>

<div class="form-group">
  <label for="address"> Address</label> <input type="text"
                                                 class="form-control" 
id="address" required

[(ngModel)]="customer.address" name="address">
</div>


<div class="btn-group">
  <button class="btn btn-primary" (click)="goBack()">Back</button>
  <a routerLink="/customers" class="btn btn-success" 
(click)="onSubmit()">Submit</a>

</div>
</form>  


3.Create-customer.component.ts

@Component({
selector: 'app-create-customer',
templateUrl: './create-customer.component.html',
styleUrls: ['./create-customer.component.css']
})



export class CreateCustomerComponent implements OnInit {
customer = new Customer;
constructor(private dataService: DataService, private locaion: Location) 
{ }
ngOnInit() {
}

add(): void {
/*console.log(this.customer);*/
this.dataService.addCustomer(this.customer);
}

onSubmit(): void {
this.add();
}
goBack(): void {
this.locaion.back();
}
}  


4.data-service.ts 

const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
providedIn: 'root'
})
export class DataService {
private customersUrl = 'http://localhost:8080/api/customers';
constructor(private http: HttpClient) { }


getCustomers(): Observable<Customer[]> {
return this.http.get<Customer[]>(this.customersUrl)
  .pipe(
    catchError(this.handleError('getCustomers', []))
  );
}


addCustomer (customer: Customer): Observable<Customer> {
console.log(customer);
return this.http.post<Customer>(this.customersUrl, customer, httpOptions)
  .pipe(
  catchError(this.handleError<Customer>('addCustomer'))
);
}

private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
  console.error(error); // log to console instead
  return of(result as T);
};
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...