【问题标题】:ERROR TypeError: Cannot set property selectedContact of [object Object] which has only a getter错误类型错误:无法设置只有 getter 的 [object Object] 的属性 selectedContact
【发布时间】:2019-02-24 10:49:53
【问题描述】:

我有一个班级联系人:

export class Contact
{
  public Id: string = '';
  public FirstName: string = '';
  public LastName: string = '';
  public Email: string = '';
  public Description: string = '';
  public Members: Array<User> = [];
  public Mute: boolean = false;   
}

我有另一个类 SelectedContact 继承了这个类

export class SelectedContact extends Contact {
    public skipMessages: number;
    public hasMessages: boolean;
    public canSendMessage: boolean;
}

我有一项服务是获取和设置 SelectedContacts

@Injectable()
export class ContactService
{
  private contactList: Array<Contact> = [];
  private selectedContactId: string;

  public get SelectedContact(): SelectedContact
  {
    const contact: Contact = this.contactList.find((v) => v.Id === this.selectedContactId);

    return contact ? contact : null;
  }

  public set SelectedContact(value: string | Contact): void
  {
    this.selectedContactId = typeof value === 'string' ? value as string : value.Id;
  }
}

然后在我的组件的 ngOnInit() 中,我试图设置我的局部变量,但出现错误:

@Component({...})
export class RightSidebarComponent implements OnInit {
    selectedContact: SelectedContact;
    ngOnInit() {
      this.selectedContact = this.contactService.SelectedContact;
    }
}

我收到以下错误:“ERROR TypeError: Cannot set property selectedContact of [object Object] which has only a getter”,在上面的行中。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    看起来this.selectedContact 在您的组件中被定义为getter。

    【讨论】:

    • 是的,这就是问题所在,它存在于代码的另一部分
    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 2020-09-26
    • 2020-08-29
    • 2020-12-24
    相关资源
    最近更新 更多