You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular路由中使用Add-Category组件编辑元素保存失败求助

Angular编辑分类保存失败问题排查与解决

问题描述

使用add-category组件同时实现分类的添加与编辑功能,添加功能正常,但编辑时出现异常:点击列表的Edit按钮可正常跳转至add-category/{ID}页面并显示待编辑分类的原有值,但保存修改时触发错误。

当前正常功能:

  • 添加新分类
  • 显示分类列表
  • 删除分类

报错详情

  1. 请求错误:POST http://localhost:5000/api/Category/SaveCategory 999
  2. 类型错误:
ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at subscribeTo (subscribeTo.js:28:1)
at innerSubscribe (innerSubscribe.js:93:35)
at push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:41:51)
at XMLHttpRequest.onLoad (http.js:1754:1)
at push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421:1)
at Object.onInvokeTask (core.js:28173:1)
at push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420:1)
at push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188:1)
at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:503:1)
at invokeTask (zone.js:1671:1)

相关代码

add-category组件代码

import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../../../services/category.service';
import { FormBuilder, FormControl, FormGroup, FormsModule, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { CategoryDTO } from '../../../models/generics/category.model';
import { DialogService } from '../../../services/dialog.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ListCategoriesComponent } from '../list-categories/list-categories.component';


@Component({
  selector: 'app-add-category',
  templateUrl: './add-category.component.html',
  styleUrls: ['./add-category.component.css']
})
export class AddCategoryComponent implements OnInit {
 
  categoryForm : FormGroup;
  category: CategoryDTO;
  categoryID : number;

  constructor(
    public categoryService : CategoryService, 
    private formBuilder: FormBuilder,
    private router: Router,
    private route : ActivatedRoute,
  ) { 

  }

  goToListCategories() {
    this.router.navigate(['list-categories'])
  }

  ngOnInit(): void {
    this.category = new CategoryDTO();
    this.createForm();

    if (this.route.snapshot.params["ID"] != null) {
      const categoryID = this.route.snapshot.params['ID'];
      this.categoryService.getCategoriaByID(categoryID).subscribe(category => {
        this.category = category;
        this.categoryForm.patchValue({
          Nome: category.Nome,
          Descrizione: category.Descrizione,
          EtichettaBreve: category.EtichettaBreve
        });
      });
    }
  }
  
  onSaveEdit() {
    if (this.categoryForm.valid) {
      this.category.Nome = this.categoryForm.controls['Nome'].value;
      this.category.Descrizione = this.categoryForm.controls['Descrizione'].value;
      this.category.EtichettaBreve = this.categoryForm.controls['EtichettaBreve'].value;
      this.categoryService.saveCategory(this.category).subscribe(() => {
        DialogService.Success("Salvataggio effettuato con successo!");
        this.router.navigate(['/list-categories']);
        this.saveFunction();
      });
    } 
  }
  
  onSubmit(): void {
    //check form
    //let CategoryDTO: any;CategoryDTO
    //this.categoryService.saveCategory(this.category).subscribe( res => { console.log('Categoria salvata', res)}),
    //                                                         err => { console.log('Errore', err)};
  }

  createForm() {
    this.categoryForm = this.formBuilder.group({
      Nome: ['', Validators.required],
      Descrizione: ['', Validators.required],
      EtichettaBreve: ['', Validators.required]
    })
  }

  saveFunction(){
    this.category.Nome = this.categoryForm.controls['Nome'].value
    this.category.Descrizione = this.categoryForm.controls['Descrizione'].value
    this.category.EtichettaBreve = this.categoryForm.controls['EtichettaBreve'].value
    
    this.categoryService                               
    .saveCategory(this.category)
    .subscribe((res: any) => {
      DialogService.Success("Salvataggio effettuato con successo!");
      this.router.navigate(['/list-categories']);
    })                       
  }
}

CategoryService的saveCategory方法

saveCategory(category: CategoryDTO): Observable<CategoryDTO> {
  return this.http.post<any>(environment.apiFullUrl + '/Category/SaveCategory', category);
}

问题分析与解决方案

1. 重复调用保存方法导致异常

在onSaveEdit方法中,订阅saveCategory成功后又调用了saveFunction,导致重复发送POST请求,且组件导航后状态异常,直接触发错误。

修复: 移除onSaveEdit中的this.saveFunction()调用:

onSaveEdit() {
  if (this.categoryForm.valid) {
    this.category.Nome = this.categoryForm.controls['Nome'].value;
    this.category.Descrizione = this.categoryForm.controls['Descrizione'].value;
    this.category.EtichettaBreve = this.categoryForm.controls['EtichettaBreve'].value;
    this.categoryService.saveCategory(this.category).subscribe(() => {
      DialogService.Success("Salvataggio effettuato con successo!");
      this.router.navigate(['/list-categories']);
    });
  } 
}

2. 类型声明与实际返回值不匹配

saveCategory方法声明返回Observable<CategoryDTO>,但实际返回Observable<any>,虽不一定直接报错,但易引发类型相关问题。

修复: 保持类型一致:

saveCategory(category: CategoryDTO): Observable<CategoryDTO> {
  return this.http.post<CategoryDTO>(environment.apiFullUrl + '/Category/SaveCategory', category);
}

3. 确认分类ID是否正确传递

编辑时需确保category对象包含ID字段,后端才能识别是编辑操作而非新增。可在ngOnInit中打印this.category确认ID是否存在:

this.categoryService.getCategoriaByID(categoryID).subscribe(category => {
  this.category = category;
  console.log('当前编辑分类:', this.category); // 检查是否包含ID
  this.categoryForm.patchValue({
    Nome: category.Nome,
    Descrizione: category.Descrizione,
    EtichettaBreve: category.EtichettaBreve
  });
});

4. 优化表单值赋值逻辑

手动逐个字段赋值冗余,可使用对象扩展或patchValue简化:

onSaveEdit() {
  if (this.categoryForm.valid) {
    // 合并原有分类数据与表单新值
    this.category = { ...this.category, ...this.categoryForm.value };
    this.categoryService.saveCategory(this.category).subscribe({
      next: () => {
        DialogService.Success("Salvataggio effettuato con successo!");
        this.router.navigate(['/list-categories']);
      },
      error: (err) => {
        console.error('保存失败:', err);
        // 可添加错误提示弹窗
      }
    });
  } 
}

内容的提问来源于stack exchange,提问作者Jany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:17:05