簡體   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