typescript 错误类型错误:无法设置只有getter的[object Object]的属性selectedContact

laik7k3q  于 2022-12-30  发布在  TypeScript
关注(0)|答案(1)|浏览(253)

我有课联系人:

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

我收到以下错误:“错误类型错误:无法设置[object Object]的属性selectedContact,该属性在上面的行中只有getter”“。

zbwhf8kr

zbwhf8kr1#

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

相关问题