【问题标题】:Argument of type 'Event' is not assignable to parameter of type“事件”类型的参数不可分配给类型的参数
【发布时间】:2021-10-15 02:41:28
【问题描述】:

编辑类别组件.html:

<app-form-category *ngIf="model" [model]="model"
(onSaveChanges)="saveChanges($event)"></app-form-category>

<mat-spinner *ngIf="!model"></mat-spinner>

edit-category.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { categoryCreationDTO, categoryDTO } from 'src/app/models/category';
import { CategoriesService } from 'src/app/services/categories.service';

@Component({
  selector: 'app-edit-category',
  templateUrl: './edit-category.component.html',
  styleUrls: ['./edit-category.component.scss']
})
export class EditCategoryComponent implements OnInit {

  constructor(
    private activatedRoute: ActivatedRoute,
    private categoriesService: CategoriesService,
    private router: Router
  ) { }

  model!: categoryDTO;

  ngOnInit(): void {
    this.activatedRoute.params.subscribe(params => {
      this.categoriesService.getById(params.id).subscribe(category =>{
        this.model = category;
      })
    });
  }

  saveChanges(categoryCreationDTO: categoryCreationDTO) {
    this.categoriesService.edit(this.model.id, categoryCreationDTO)
    .subscribe(()=>{
      this.router.navigate(["/magazine"])
    })
  }
}

category.ts

export interface categoryCreationDTO{
  name: string;
}

export interface categoryDTO{
  id: number;
  name: string;
}

错误

错误: src/app/components/magazine/category/edit-category/edit-category.component.html:2:30

  • 错误 TS2345:“事件”类型的参数不可分配给“类别创建 DTO”类型的参数。缺少属性“名称” 在“Event”类型中,但在“categoryCreationDTO”类型中是必需的。

(onSaveChanges)="saveChanges($event)"> ~~~~~~

src/app/components/magazine/category/edit-category/edit-category.component.ts:8:16 templateUrl: './edit-category.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件EditCategoryComponent的模板出错。

我不明白这个错误,有人可以帮助我吗?

【问题讨论】:

    标签: html angular typescript forms


    【解决方案1】:

    saveChanges 方法需要具有 categoryCreationDto 类型的对象,该对象本身需要具有 name 属性(正如您在参数继承的接口上定义的那样)。当您将$event 传递给saveChanges($event) 时,事件属性上没有name。如果你不知道 event 是什么类型的对象,你可以 console.log() 它并正确传递给方法。

    我看到您尝试通过OnSaveChanges 属性从子组件中使用eventEmitter -> 查看从子组件发送到父组件的内容并在saveChanges 中相应地使用它。 $event 对象将正是您通过 EventEmitter 从子 app-form-category 输出的对象。

    【讨论】:

      【解决方案2】:

      Typescript 期望事件响应为您指定的类型,但实际上,它会键入 Event

      您可能想尝试来自事件的内容,然后将所需的内容分配给 api 调用。

      【讨论】:

        猜你喜欢
        • 2021-05-17
        • 2022-07-08
        • 2021-06-30
        • 2019-06-24
        • 2021-06-14
        • 2021-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多