【问题标题】:Angular, the newly added item can only be deleted after refreshAngular,新添加的项刷新后才能删除
【发布时间】:2022-01-11 00:24:14
【问题描述】:

我正在开发一个 Angular 12 项目,我正在使用 JSON-server 存储数据。 CRUD 操作运行良好。

但是当我使用表单添加新项目时,deleteupdate 按钮将不起作用,除非我刷新页面。

This the error I get in the console,点击删除按钮后,(不刷新)。

product.service.ts

  url = environment.url + 'products/';
  constructor(private http: HttpClient) {}

  getListProduct() {
    return this.http.get<Product[]>(this.url);
  }

  addProduct(product: Product) {
    return this.http.post(this.url, product);
  }

  deleteProduct(id: string) {
    return this.http.delete(this.url + id);
  }
  updateProduct(product: Product) {
    return this.http.put(this.url + product.id, product);
  }
}

main-product.component.ts

export class MainProductComponent implements OnInit {
 inputProduct: Product = new Product();
 isForm: Boolean = false;
 buttonString: String = 'Add New Product';
 listProduct: Product[] = [];

 constructor(private productService: ProductService) {}

 ngOnInit(): void {
   this.productService
     .getListProduct()
     .subscribe((data: Product[]) => (this.listProduct = data));
 }
 changePage() {
   this.isForm = !this.isForm;
   if (this.isForm) {
     this.buttonString = 'Go Back To List';
   } else {
     this.inputProduct = new Product();
     this.buttonString = 'Add New Product';
   }
 }
 deleteProduct(p: Product) {
   let i = this.listProduct.indexOf(p);
   this.productService
     .deleteProduct(p.id)
     .subscribe(() => this.listProduct.splice(i, 1));
 }
 saveProduct(product: Product) {
   let i = this.listProduct.indexOf(product);
   if (i != -1) {
     //update a product
     this.productService
       .updateProduct(product)
       .subscribe(() => (this.listProduct[i] = product));
   } else {
     //add a new product
     this.productService.addProduct(product).subscribe(
       () => this.listProduct.push(product),
       () => console.log('error')
     );
   }
   this.isForm = false;
   this.buttonString = 'Add New Product';
   this.inputProduct = new Product();
 }

 updateProduct(p: Product) {
   this.isForm = true;
   this.inputProduct = p;
 }

form-product.component.ts

export class FormProductComponent implements OnInit {
  selectedFile = null;
  private product!: Product;
  productForm!: FormGroup;
  @Input() updateProduct!: Product;
  @Output() addEvent = new EventEmitter<Product>();
  constructor(private builder: FormBuilder) {}

  ngOnInit(): void {
    if (this.updateProduct === null) {
      this.product = new Product();
    } else {
      this.product = this.updateProduct;
    }

    this.productForm = this.builder.group({
      title: [
        this.product.libelle,
        [Validators.required, Validators.minLength(3)],
      ],
      price: [
        this.product.prixUnitaire,
        [Validators.required, Validators.min(10)],
      ],
      photo: [this.product.photo, Validators.required],
      category: [this.product.categorie, Validators.required],
    });
  }
  upload(event: any) {
    this.selectedFile = event.target.files[0].name;
    console.log(this.selectedFile);
  }
  addProduct() {
    this.product.libelle = this.productForm.value.title;
    this.product.prixUnitaire = this.productForm.value.price;
    this.product.photo = String(this.selectedFile);
    this.product.categorie = this.productForm.value.category;

    this.addEvent.emit(this.product);
  }
}

【问题讨论】:

    标签: angular typescript httpclient angular12 json-server


    【解决方案1】:

    很难确定,但看起来您并没有保存前端数组中创建的响应。

    最有可能的代码应该如下

    // add a new product
         this.productService.addProduct(product).subscribe(
           newProduct => this.listProduct.push(newProduct),
           () => console.log('error')
         );
    

    上面是我在手机上快速写的,这里有更详细的答案。

    我以前从未使用过json-server,所以这对我来说是个未知数。从他们的文档中,在他们的示例中,他们在将对象发送到 json 服务器之前在对象上创建了 id。我看不到您的产品类别,所以我不知道您是否正在为您的对象生成 id...我猜不是。

    此类最常见的工作流程是前端将创建一个没有 id 的对象,然后将其发送到后端,后端会将其保存在某种数据存储中。该过程还为该对象生成 id 并将其作为对象的一部分从 create 调用中返回。然后前端可以通过 id 对该对象执行进一步的操作(get、put、delete 等)。

    在您的代码中,您没有获取后端返回的对象并将其推送到您的数组中,而是将您发送到后端的对象推送到您的数组中。同样,在没有 id 的典型场景中。

    如果 json-server 要求您创建和分配 id,那么您需要更新您的产品类以在更新时分配一个 id。

    您必须从数组中获取产品的逻辑正在运行,因为您得到的错误不是它找不到“未定义的 id”,而是代码正在查找产品,而是 id 属性该产品对象未定义。

    同样,通常该 id 来自后端,如果这里发生这种情况,那么您将不会得到它,因为您没有将来自后端的对象添加到您的数组中。如果 json-server 要求您将 id 传递给它,那么您将需要更新前端代码以生成 id,然后一切都应该为您工作。

    【讨论】:

    • 感谢您的回复,但仍然无法正常工作:(
    • 你可能还需要显示你的后端代码
    • 没有后端代码,我使用 JSON-server 作为数据库。还有什么我应该在我的问题中包括的吗?谢谢
    • @MariemBokri 我更新了我的答案以提供更多详细信息,以帮助您弄清楚这里发生了什么。希望对您有所帮助!
    • 非常感谢!那真的很有帮助。现在我的前端代码生成了新产品的 id,一切正常
    【解决方案2】:

    peinearydevelopment 是对的。您也可以在添加或删除后重新获取列表。 (如果您想运行一些计算和查询或为列表设置一些服务器端排序)

    类似:

    constructor(private productService: ProductService) {}
    
     ngOnInit(): void {
       this.fetchList();                                                  // This Line
     }
    
     fetchList() {                                                        // This Function
       this.productService
         .getListProduct()
         .subscribe((data: Product[]) => (this.listProduct = data));
     }
     deleteProduct(p: Product) {
       let i = this.listProduct.indexOf(p);
       this.productService
         .deleteProduct(p.id)
         .subscribe(() => {
           this.fetchList();                                              // This Line
         });
     }
     saveProduct(product: Product) {
       let i = this.listProduct.indexOf(product);
       if (i != -1) {
         //update a product
         this.productService
           .updateProduct(product)
           .subscribe(() => (this.listProduct[i] = product));
       } else {
         //add a new product
         this.productService.addProduct(product).subscribe(() => {
           this.fetchList();                                              // This Line
         }, () => console.log('error'));
       }
       this.isForm = false;
       this.buttonString = 'Add New Product';
       this.inputProduct = new Product();
     }
    

    【讨论】:

    • 非常感谢您的回复 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多