如何通过路由编辑 Angular 中的元素?

问题描述 投票:0回答:0

这是我的第一个问题。 我实际上是作为全栈开发人员学习的,但我一直坚持使用 ActivatedRoute 和路由的东西。

我有两个组件(添加类别和列表类别),我希望第一个组件能够添加和编辑元素。添加功能已实现,但我对编辑功能有疑问。

当我单击“编辑”时,我被重定向到 add-category/{ID},其中包含要编辑的值,这很好,但我无法保存它。

我的意图是有两个组件(列表类别和添加类别)并使用它们分别显示类别数组并有可能编辑或添加新元素。

实际工作: - 添加新元素。 -显示元素列表。 -删除元素。

现在我在每个列表元素旁边都有“编辑”按钮,单击它会将我重定向到“localhost ......./{ID}”,在那里我可以看到元素的实际值。当我尝试保存编辑后的元素时,出现错误。

  1. 发布

    http://localhost:5000/api/Category/SaveCategory 999

  2. “错误类型错误:您在需要流的位置提供了‘未定义’。您可以提供 Observable、Promise、Array 或 Iterable。 在 subscribeTo (subscribeTo.js:28:1) 在 innerSubscribe (innerSubscribe.js:93:35) 在推送../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:41:51) 在 XMLHttpRequest.onLoad (http.js:1754:1) 在推送../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421:1) 在 Object.onInvokeTask (core.js:28173:1) 在推送../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420:1) 在推送../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188:1) 在 push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:503:1) 在 invokeTask (zone.js:1671:1)"

我正在尝试使用添加类别来添加和编辑一个元素,但我只想做第一个。

这是我的添加类别组件:

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
        });
      });
    }

    /*if (this.route.snapshot.params["ID"] != null) {
      this.categoryService.getCategoriaByID(this.route.snapshot.params["ID"]); 

    */

    
    /*  const categoryId = this.route.snapshot.params['ID'];
      if (categoryId != null) {
        this.categoryService.getCategoriaByID(categoryId).subscribe(category => {
          this.category = category;
          this.categoryForm.patchValue({
            Nome: category.Nome,
            Descrizione: category.Descrizione,
            EtichettaBreve: category.EtichettaBreve
          });
        });
      } else {
        this.category = new CategoryDTO();
      }  
    } 
    }*/
  }
  

  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);

}

c# angular typescript routes edit
© www.soinside.com 2019 - 2024. All rights reserved.