Не удалось отправить сообщение снова после ошибки статуса 400 даже после исправления запроса - PullRequest
1 голос
/ 02 апреля 2020

У меня есть страница редактирования продукта. Я редактирую и продукт. Если я отредактирую название продукта с уже существующим продуктом с таким именем и отправлю запрос на публикацию в Java Spring REST API, используя JWT. У меня есть проверка, и она возвращает правильное состояние 400.
Но проблема в , что без перезагрузки страницы, когда я исправляю поле имени и повторно отправляю его, отображается состояние 400 снова с тем же сообщением об ошибке. Это моя функция отправки:

 onSubmit() {
    this.productSubmit = true;
    if (
      this.productFormGroup.valid &&
      !this.isTableEmpty &&
      this.isFormValid &&
      !this.isCustomTableEmpty
    ) {
      this.isLoading = true;
      this.product.name = this.f.name.value;
      this.product.productCategory = this.f.category.value;
      this.product.model = this.f.model.value;
      this.product.barcode = this.f.barcode.value;
      this.product.unit = this.f.unit.value;
      this.product.manufacturer = this.f.manufacturer.value;
      this.product.cost = this.f.cost.value;
      this.product.minimumStockLevel = this.f.minStock.value;
      this.product.description = this.f.description.value;
      this.product.length=this.f.length.value;
      this.product.width=this.f.width.value;
      this.product.height=this.f.height.value;
      this.product.weight=this.f.weight.value;
       if (this.f.brand.value) {
        this.product.brand = this.f.brand.value;
      } else {
        this.product.brand = null;
      }
      if (this.f.foreignName.value) {
        this.product.foreign_name=this.f.foreignName.value;
      } else {
        let foreignName=this.f.name.value;
        this.product.foreign_name=foreignName;
      }
      if (this.f.foreignSKU.value) {
        this.product.foreign_sku=this.f.foreignSKU.value;
      } else {
        let foreignSKU=this.f.model.value;
        this.product.foreign_sku=foreignSKU;
      }
      if (this.f.preferred_supplier.value) {
        this.product.preferred_supplier=this.f.preferred_supplier.value;
      } else {
        this.product.preferred_supplier=null;
      }
      this.product.prices = this.myPriceLists;
      let id = null;
      if (this.activatedRoute.snapshot.params["id"]) {
        id = this.activatedRoute.snapshot.params["id"];
      } else {
        this.router.navigate(["/loggedIn", "product", "list"]);
      }
      this.product.productCategory = this.selectedCategory;

      this.formData.append(
        "product",
        new Blob(
          [JSON.stringify(this.product, this.appService.jsonStringifier)],
          { type: "application/json" }
        )
      );

      this.images = this.images.concat(this.product.productImages);
      for (let image of this.images) {
        this.formData.append("images", image);
      }
      this.productService.updateProduct(this.formData, id).subscribe(
        () => {
          this.productService.resetProducts();
          this.messageService.add({
            severity: "info",
            summary: "Success",
            detail: "Product Successfully Edited"
          });
          this.router.navigate(["/loggedIn", "product", "list"]);
        },
        (errorResponse : HttpErrorResponse) => {
          this.productErrors = this.appService.errorObjToMap(
            errorResponse.error.errors
          );
          this.productSuccess = errorResponse.error.success;
          this.isLoading = false;
          this.messageService.add({
            severity: "error",
            summary: "Failure",
            detail: "Product not edited."
          });
         console.log(errorResponse.error.errors[0].message);

        },
        () => {
          this.successAlert = true;
          this.isLoading = false;
        }
      );
    }
  }

* Так выглядит мой REST-контроллер для этого запроса *

    @RequestMapping(value = "save/{id}", method = RequestMethod.POST)
    public ResponseEntity addProduct(@PathVariable("id") Integer id, @Valid @RequestPart Product product, @RequestPart MultipartFile[] images, BindingResult bindingResult, HttpServletRequest request) throws IOException {
        return saveProduct(id, product, images, bindingResult, request);
    }

Все отлично работает, кроме этого. Я надеюсь, что вы можете понять проблему. Если у вас есть какие-либо вопросы, спросите меня или что-то, что я мог бы пропустить.

1 Ответ

0 голосов
/ 02 апреля 2020

Вы должны попытаться переустановить объект messageService после

console.log(errorResponse.error.errors[0].message);

Я не знаком с Angular, но реагирую и поэтому предложил ответ с этой точки зрения.

...