表单值未添加到数据库

时间:2019-01-04 15:24:19

标签: java angular

enter image description here

我正在使用angular通过调用java api来插入新的客户对象,但是未插入客户对象。从表单提交的客户对象未插入数据库中。但是getCustomers()方法确实可以工作。表单数据正在通过data.service.ts的addCustomer(customer:Customer)方法获取,但未添加到数据库中。

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);
};
}
}

0 个答案:

没有答案