Angular 如何将数据发布到数据库中最新添加的资源/记录?
我想使用post方法将特定数据发布到数据库中的现有记录中。我插入它的行是空的。每次我发布一些东西,它就会创造一个新的记录。最简单的方法是什么 我使用Angular作为前端,Glassfish RESTful服务器作为后端 类型脚本文件:Angular 如何将数据发布到数据库中最新添加的资源/记录?,angular,typescript,rest,http,Angular,Typescript,Rest,Http,我想使用post方法将特定数据发布到数据库中的现有记录中。我插入它的行是空的。每次我发布一些东西,它就会创造一个新的记录。最简单的方法是什么 我使用Angular作为前端,Glassfish RESTful服务器作为后端 类型脚本文件: export class MenuComponent implements OnInit { public codeValue: string; baseurl = 'http://localhost:8080/aquadine-jee/resour
export class MenuComponent implements OnInit {
public codeValue: string;
baseurl = 'http://localhost:8080/aquadine-jee/resources/restaurant';
// Empty array of menu list
codeList = [];
// List of Mcdonalds menu
codeListMcd = [
{menu: 'Hamburger menu'},
{menu: 'Big mac menu'},
{menu: 'Quarter Pounder menu'},
{menu: 'Maestro burger menu'},
{menu: 'Big Tasty menu'}
];
// List of Kentucky Fried chicken menu
codeListKfc = [
{menu: 'Chicken burger menu'},
{menu: 'Chicken bucket menu'},
{menu: 'Spicy chicken menu'},
{menu: 'Tender chicken menu'},
{menu: 'Chicken nuggets menu'}
];
// List of Burger King menu
codeListBk = [
{menuid: 1, menu: 'Whopper burger menu', price: 3.50},
{menuid: 2, menu: 'Texas Bacon king menu', price: 5.50},
{menuid: 3, menu: 'Double Steakhouse menu', price: 5.50},
{menuid: 4, menu: 'Chili Cheese burger menu', price: 6.50},
{menuid: 5, menu: 'Chicken Tendercrisp menu', price: 6.50}
];
// List of Dominos pizza menu
codeListDp = [
{menuid: 1, menu: 'Pizza Shoarma menu', price: 3.50},
{menuid: 2, menu: 'Pizza Roasted veggie menu', price: 5.50},
{menuid: 3, menu: 'Pizza Bbq mixed grill menu', price: 5.50},
{menuid: 4, menu: 'Pizza Hawaii menu', price: 6.50},
{menuid: 5, menu: 'Pizza Americana menu', price: 6.50}
];
// List of New York pizza menu
codeListNyp = [
{menu: 'Pizza Double Tasty menu'},
{menu: 'Pizza Mixed Grill menu'},
{menu: 'Pizza Margherita menu'},
{menu: 'Pizza BBQ Meatlovers'},
{menu: 'Pizza Downtown Doner menu'}
];
@ViewChild('f', {static: true}) form: NgForm;
menu = {
menuid: ' ',
menu: ' ',
price: ' '
};
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'my-auth-token'
})
};
constructor(private http: HttpClient) {
}
// Get the selected restaurant and fill the datalist with data
ngOnInit() {
this.http.get('http://localhost:8080/aquadine-jee/resources/restaurant')
.subscribe(
val => {
const restStr = val;
console.log(restStr);
console.log(restStr[0].menu);
// @ts-ignore
const restNaam = JSON.stringify(restStr[restStr.length - 1].name);
console.log(restNaam);
if (restNaam.toString() === '"Mcdonalds"') {
this.codeList = this.codeListMcd;
} else if (restNaam.toString() === '"Kentucky Fried Chicken"') {
this.codeList = this.codeListKfc;
} else if (restNaam.toString() === '"Burger King"') {
this.codeList = this.codeListBk;
} else if (restNaam.toString() === '"Dominos pizza"') {
this.codeList = this.codeListDp;
} else if (restNaam.toString() === '"New York Pizza"') {
this.codeList = this.codeListNyp;
}
}
);
}
// Method to POST the menu data to the backend
public saveMenu(e): void {
const menu = e.target.value;
const list = this.codeList.filter(x => x.menu === menu)[0];
this.menu.menu = list.menu;
// HttpHeader to give the content type
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
// Array with data assigned to a const
const data = {
menu: list.menu
};
console.log(data)
const myJsonString = JSON.stringify(data);
console.log(myJsonString.valueOf());
console.log(JSON.stringify(data) + 'test1234568910');
this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant', JSON.parse(myJsonString.valueOf()), httpOptions)
.subscribe( // subscribe to observable http.post
res => {
console.log('response' + ' ' + res); // log results otherwise log error
},
err => {
console.log('Error occured');
}
);
我正在尝试将数据发布到此链接中最新/最新添加的记录:
'http://localhost:8080/aquadine-jee/resources/restaurant'
后端代码:
package nl.aquadine.model;
import javax.persistence.*;
//@NamedQueries({
// @NamedQuery(name = "Restaurant.findOne", query = "select m from Restaurant m where m.id = :id"),
// @NamedQuery(name = "Restaurant.getAll", query = "select m from Restaurant m")
//})
/**
* @author Fethi
*/
@Entity
@Table(name = "restaurant")
public class Restaurant {
@Id
@GeneratedValue
private Long restaurantId;
private String name;
private String address;
private String menu;
public Restaurant(){
}
public Restaurant(String name, String address) {
this.name = name;
this.address = address;
this.menu = menu;
}
public Long getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Long restaurantId) {
this.restaurantId = restaurantId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMenu() {
return menu;
}
public void setMenu(String menu) {
this.menu = menu;
}
}
包nl.aquadine.rest;
进口nl.aquadine.model.Restaurant;
导入nl.aquadine.service.Impl.repositoryserviceinpl;
导入nl.aquadine.service.RepositoryService;
导入javax.ws.rs.*;
导入javax.ws.rs.core.MediaType;
导入javax.ws.rs.core.Response;
导入java.util.List;
/**
*@作者费提
*/
@小径(“餐厅”)
公共类餐厅资源{
私人寄存服务寄存服务;
公共餐厅资源(){
repositoryService=RepositoryServiceImpl.getInstance();
}
@得到
@生成(“应用程序/json”)
公众回应(全部){
List all=repositoryService.getAllRestaurants();
返回响应
.现状(200)
.header(“访问控制允许原点”、“*”)
.实体(全部)
.build();
}
@得到
@路径(“/{id}”)
@使用(“应用程序/json”)
公共响应getRestaurant(@PathParam(“id”)整数id){
Restaurant Restaurant=repositoryService.find(id);
返回响应
.现状(200)
.实体(餐厅)
.build();
}
@得到
@路径(“/name{restaurantName}”)
@使用(“应用程序/json”)
公共响应getAllRestaurantNames(@PathParam(“restaurantName”)字符串restaurantName){
restaurantNames=repositoryService.getAllRestaurantNames(restaurantName);
返回响应
.现状(200)
.实体(餐厅名称)
.build();
}
@产生(MediaType.APPLICATION_JSON)
公共列表getAllRestaurants(){
return repositoryService.getAllRestaurants();
}
/**
*拯救餐厅JSON
*@param餐厅
*@返回响应
*/
@职位
@使用(“应用程序/json”)
公众响应节约(餐厅){
系统输出打印(“测试”);
存储服务.保存(餐厅);
返回响应
.现状(201)
.build();
}
@放
@使用(“应用程序/json”)
公共空间更新(餐厅){
repositoryService.update(餐厅);
}
@删除
@路径(“/{id}”)
@使用(“应用程序/json”)
public void delete(@PathParam(“id”)整数id){
Restaurant Restaurant=repositoryService.find(id);
repositoryService.delete(餐厅);
}
}
原因是您正在使用HTTP POST
请求更新现有记录。这会导致创建新记录,而不是更新现有记录。正如我所看到的,url对于创建和更新是相同的。要区分创建或更新,应使用HTTP PUT。更改您的代码如下
this.http.put('http://localhost:8080/aquadine-jee/resources/restaurant', JSON.parse(myJsonString.valueOf()), httpOptions)
.subscribe(res => {
console.log('response' + ' ' + res); // log results otherwise log error
},
err => {
console.log('Error occured');
});
- 如果可以将API调用移动到服务类,则效果更好。
- 学习Rest API。
this.http.put('http://localhost:8080/aquadine-jee/resources/restaurant', JSON.parse(myJsonString.valueOf()), httpOptions)
.subscribe(res => {
console.log('response' + ' ' + res); // log results otherwise log error
},
err => {
console.log('Error occured');
});