【问题标题】:Type 'void' is not assignable to type 'Contact'类型 'void' 不可分配给类型 'Contact'
【发布时间】:2017-12-29 23:44:11
【问题描述】:

detail.component.ts

contact: Contact;
constructor( private contactService: LocalStorageService) {}

ngOnInit(): void {
  this.contact = this.contactService
    .getContact(815);
}

contact.service.ts

getContact(id: number) {
    var contact = 
    JSON.parse(LocalStorage.getItem("contacts")).filter((cntct) => { 
      return cntct.id == id 
    });
}

错误:类型“void”不可分配给类型“Contact”。

在这里,在网址中我有/detail/"clicked-contacts-id-number"

我想获取该联系人 ID 的联系人数据。

【问题讨论】:

  • 你应该返回联系方式。

标签: angular angular-routing angular-services


【解决方案1】:

您忘记返回联系人。你可以像这样简化你的代码

getContact(id: number) {
  return JSON.parse(LocalStorage.getItem("contacts")).filter((cntct) => { 
      return cntct.id == id });
}

【讨论】:

  • 谢谢你,但仍然在 html 组件中 {{contact.name}} 没有显示任何内容。
  • {{contact.name}}

  • @OmPatel 您返回的数据也可能为空,这就是原因。尝试在你的模板中做一个 *ngIf="contact" 来检查它是否不为空
【解决方案2】:

您没有通过获取联系方式返回联系方式

getContact(id: number) {
    var contact = 
JSON.parse(LocalStorage.getItem("contacts")).filter((cntct) => { return 
cntct.id == id });
return contact //add this line
}

【讨论】:

  • 谢谢你,但仍然在 html 组件中 {{contact.name}} 没有显示任何内容。
  • 是否存在 id 为 815 的联系人?过滤器方法也将返回一个数组。请确保您循环遍历该数组
【解决方案3】:

你还没有在contact.service.ts中定义getContact()函数的返回类型。

试试这个..

getContact(id: number): 联系人{

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2021-09-23
    • 2017-09-21
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2019-05-06
    • 2020-10-01
    相关资源
    最近更新 更多