繁体   English   中英

如何使用 angular 和 springboot 添加新产品?

[英]How can I add new product using angular and springboot?

我需要在我的桌子上添加一个新产品。 这在 Postman 上工作http://localhost:8080/product/create/ 当我发布并添加新产品时,它会返回 id 并自动将其添加到我的表中。 我的问题是如何在 angular CLI 上实现它。 我不知道我会怎么做。 有人可以帮助我吗? 这是我的代码:

产品控制器.java

@PostMapping("/product/create/")
private int saveProduct(@RequestBody Products products)
{
   productsService.save(products);
   return products.getId();
}

app.component.ts

ngOnInit() {
    this.getProduct();
  }
  public getProduct(): void {
    this.productServive.getProduct().subscribe(
      (response: Product[]) => {
        this.products = response;
      },
      (error: HttpErrorResponse)=> {
        alert(error.message);
      }
    )
  }

  public onAddProduct(addForm: NgForm): void {
    this.productServive.addProduct(addForm.value).subscribe(
      (response: Product) => {
        console.log(response);
        this.getProduct();
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    );
  }

产品.service.ts

private apiServerUrl = environment.apiBaseUrl;

  constructor(private http: HttpClient) { }

  public getProduct() : Observable<Product[]> {
    return this.http.get<Product[]>(`${this.apiServerUrl}/products/hasstocks`);
  }

  public addProduct(product: Product) : Observable<Product> {
    return this.http.post<Product>(`${this.apiServerUrl}/product/create/`, product);
  }

app.component.html

  <form #addForm="ngForm" (ngSubmit)="onAddProduct(addForm)">
    <div class="mb-3">
      <label for="name" class="col-form-label">Name:</label>
      <input type="text" class="form-control" id="name" ngForm name="name">
    </div>
    <div class="mb-3">
      <label for="description" class="col-form-label">Description:</label>
      <input type="text" class="form-control" id="description" ngModel name="description">
    </div>
    <div class="mb-3">
      <label for="sku" class="col-form-label">SKU:</label>
      <input type="text" class="form-control" id="sku" ngModel name="sku">
    </div>
    <div class="mb-3">
      <label for="price" class="col-form-label">Price:</label>
      <input type="text" class="form-control" id="price" ngModel name="price">
    </div>
    <div class="mb-3">
      <label for="quantity" class="col-form-label">Quantity:</label>
      <input type="text" class="form-control" id="quantity" ngModel name="quantity">
    </div>
    <div class="float-end">
      <button [disabled]="addForm.invalid" type="button" class="btn btn-primary">Add Product</button>
    </div>
  </form>

它不能在一起,您必须将 2 个方法分开为 save 和 getProduct 但您可以附加 getProduct 方法和页面,当您保存产品并刷新页面时,它似乎会自动将其添加到您的表中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM