简体   繁体   English

无法分配给 object '[object Object]' 的只读属性 'winner'

[英]Cannot assign to read only property 'winner' of object '[object Object]'

I'm encountering the error我遇到了错误

ContestDetailsModalComponent.html:21 ERROR TypeError: Cannot assign to read only property 'winner' of object '[object Object]'
    at ContestDetailsModalComponent.onWinner (contest-details-modal.component.ts:88:24)
    at Object.eval [as handleEvent] (ContestDetailsModalComponent.html:21:17)
    at handleEvent (core.js:43993:77)
    at callWithDebugContext (core.js:45632:1)
    at Object.debugHandleEvent [as handleEvent] (core.js:45247:1)
    at dispatchEvent (core.js:29804:1)
    at core.js:42925:1
    at HTMLButtonElement.<anonymous> (platform-browser.js:2668:1)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399:1)
    at Object.onInvokeTask (core.js:39680:1)

when I try to make the assignment当我尝试做作业时

this.contest.winner = winnerId; this.contest.winner = winnerId;

you see in the following code snippet:您在以下代码片段中看到:

public onWinner(winnerId: number): void {
     const post: Post = new Post();
     post.title = `The winner of the contest has been elected: ${this.contest.title}`;
     post.description = `Tizio has been elected winner of the contest and ${this.user.name} gives him the most welcome compliments`;
     post.user = this.user;
     post.contest = this.contest;
     post.type = Type.WINNER;
     post.level = Level.SUCCESS;
     this.contest.winner = winnerId;
     this.store.dispatch(PostActions.savePost({post}));
     this.store.dispatch(ContestActions.saveContest({contest: this.contest}));
}

I've done this kind of assignment with other classes around the project and they never bothered me.我和项目周围的其他班级一起完成了这种作业,他们从来没有打扰过我。

I enclose the contest class and post if it is useful:我附上比赛 class 并发布是否有用:

export class Contest {
  public id: number;
  public title: string;
  public description: string;
  public rules: string;
  public startDate: Date;
  public endDate: Date;
  public status: Status;
  public winner: number;
  public bannedUser: number[];
}


export class Post {
  public id: number;
  public title: string;
  public description: string;
  public level: Level;
  public type: Type;
  public user: User;
  public publishDate: Date;
  public contest: Contest;

}

I also tried some solutions always found on this forum such as:我还尝试了一些总是在这个论坛上找到的解决方案,例如:

Object.assign(target, source); Object.assign(目标,来源);

But he rightly tells me that this.contest.winner is null or undefined.但他正确地告诉我 this.contest.winner 是 null 或未定义。

I hope for your help.我希望得到你的帮助。 Thank you谢谢

Edit :编辑

This is the entire component.ts where onWinner() is present.这是存在 onWinner() 的整个 component.ts。

@Component({
  selector: 'app-contest-details-modal',
  templateUrl: './contest-details-modal.component.html',
  styleUrls: ['./contest-details-modal.component.scss'],
})
export class ContestDetailsModalComponent implements OnInit, OnDestroy, AfterViewChecked {
  private readonly subscriptions: Subscription = new Subscription();
  public id: number;
  public user: User;
  public contest: Contest;
  public images: Image[];
  public hasVoted: boolean;

  constructor(
    private readonly bsModalRef: BsModalRef,
    private readonly modalService: BsModalService,
    private readonly store: Store<AppState>,
    private cdRef: ChangeDetectorRef
  ) { }

  public ngOnInit(): void {

    this.subscriptions.add(this.store.pipe(select(AuthSelectors.getUser)).subscribe((user: User) => {
      if (user) {
        this.user = user;
      }
    }));

    this.subscriptions.add(this.store.pipe(select(ContestSelectors.getById)).subscribe((contest: Contest) => {
      if (contest) {
        this.contest = contest;
      }
    }));

    this.subscriptions.add(this.store.pipe(select(ImageSelectors.getImages)).subscribe((images: Image[]) => {
      if (images.length) {
        this.images = images;
      }
    }));

    this.subscriptions.add(this.store.pipe(select(UserSelectors.check)).subscribe((ack: Ack) => {
      if (ack) {
        this.store.dispatch(AuthActions.updatedUser({userId: this.user.id}));
        this.modalService.show(UploadImageModalComponent);
        this.bsModalRef.hide();
      }
    }));

    this.subscriptions.add(this.store.pipe(select(ImageSelectors.check)).subscribe((ack: Ack) => {
      if (ack) {
        this.bsModalRef.hide();
      }
    }));

  }

  public ngOnDestroy(): void {
    this.store.dispatch(UserActions.clean());
    this.store.dispatch(ContestActions.clean());
    this.subscriptions.unsubscribe();
  }

  public onWinner(winnerId: number): void {
    const post: Post = new Post();
    post.title = `The winner of the contest has been elected: ${this.contest.title}`;
    post.description = `Tizio has been elected winner of the contest and ${this.user.name} gives him the most welcome compliments`;
    post.user = this.user;
    post.contest = this.contest;
    post.type = Type.WINNER;
    post.level = Level.SUCCESS;
    this.contest.winner = winnerId;
    this.store.dispatch(PostActions.savePost({post}));
    this.store.dispatch(ContestActions.saveContest({contest: this.contest}));
  }

  public onJoin(): void {
    this.store.dispatch(UserActions.saveUser({idUser: this.user.id, id: this.contest.id}));
  }

  public onVote(image: Image): void {
    let vote: number = image.vote;
    vote = vote + 1;
    this.store.dispatch(ImageActions.updateImage({photoId: image.id, votes: vote, userId: this.user.id}));
    this.store.dispatch(AuthActions.updatedUser({userId: this.user.id}));
  }

  public isContain(contestId: number): boolean {
    if (this.user.myContest) {
      for (const i of this.user.myContest) {
        if (contestId === i) {
          return true;
        }
      }
    }
    return false;
  }

  public isImageVoted(id: number): boolean {
    if (this.user.favouritePhoto) {
      for (const imageVoted of this.user.favouritePhoto) {
            if (id === imageVoted) {
              this.hasVoted = true;
              return true;
            }
      }
      return false;
      }
   }

  public onBan(image: Image): void {
    this.modalService.show(BanModalComponent, {initialState : image});
    this.bsModalRef.hide();
  }

  public isBan(contestId: number): boolean {
    if (this.user.whereBanned) {
      for (const contestBanned of this.user.whereBanned) {
        if (contestId === contestBanned) {
          return true;
        }
      }
      return false;
    }
  }

  public ngAfterViewChecked(): void {
      this.cdRef.detectChanges();
  }
}

contest contains a reference to an Observable emission, and all references emitted by Observables are readonly. contest包含对 Observable emission 的引用,并且 Observables 发出的所有引用都是只读的。 Either clone contest :要么克隆contest

this.contest = { ...contest };

Or, better, leave it as an Observable and consume it as such, generally via the async pipe. Also, if you're using NgRx, you want to be using store.select() :或者,更好的是,将其保留为 Observable 并按原样使用它,通常通过async pipe。此外,如果您使用的是 NgRx,则需要使用store.select()

this.contest$ = this.store.select(ContestSelectors.getById);

无法分配给 object '# 的只读属性'property'<object> '<div id="text_translate"><p> 我有这个问题。</p><p> 带接口:</p><pre> export interface IDevice { id: string, selected: boolean }</pre><p> 通过以下方式创建实例:</p><pre> let newDevice: IDevice = { id: uuid4(), selected: false, } as IDevice;</pre><p> 它被添加到 recoil state 中的数组中,并在 React 中用于 function 中,其中数组已使用 useRecoilState() 检索。 const [leftList, setLeftList] = React.useState&lt;IDevice[]&gt;([]);</p><p> 现在它在处理程序中用于选择列表控件上的设备,这里发生错误:</p><pre> ... leftList.map((item: IDevice) =&gt; { if (item.id === event.dataItem.id) { item.selected =.item;selected; } return item. })...</pre><p> 我收到错误消息:无法分配给 object '#' 的只读属性 'selected'</p><p> 即使首先通过 [...leftList] 克隆数组也无济于事。</p><p> 我迷路了:-)希望有人能对此有所了解吗?</p></div></object> - Cannot assign to read only property 'property' of object '#<Object>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法分配给对象 &#39;# 的只读属性<Object> &#39; - Cannot assign to read only property of object '#<Object>' 无法分配给 object '[object Object]' 的只读属性 'name' - Cannot assign to read only property 'name' of object '[object Object]' 无法分配给 # 的只读属性“.js”<Object> - Cannot assign to read only property '.js' of #<Object> 无法分配给 object 的只读属性“displayName” - Cannot assign to read only property 'displayName' of object 无法分配给 object 的只读属性 - cannot assign to read-only property of object Ngrx:无法分配给对象“[Object]”的只读属性“Property” - Ngrx : Cannot assign to read only property 'Property' of object '[Object]' 无法分配给 object '# 的只读属性'property'<object> '<div id="text_translate"><p> 我有这个问题。</p><p> 带接口:</p><pre> export interface IDevice { id: string, selected: boolean }</pre><p> 通过以下方式创建实例:</p><pre> let newDevice: IDevice = { id: uuid4(), selected: false, } as IDevice;</pre><p> 它被添加到 recoil state 中的数组中,并在 React 中用于 function 中,其中数组已使用 useRecoilState() 检索。 const [leftList, setLeftList] = React.useState&lt;IDevice[]&gt;([]);</p><p> 现在它在处理程序中用于选择列表控件上的设备,这里发生错误:</p><pre> ... leftList.map((item: IDevice) =&gt; { if (item.id === event.dataItem.id) { item.selected =.item;selected; } return item. })...</pre><p> 我收到错误消息:无法分配给 object '#' 的只读属性 'selected'</p><p> 即使首先通过 [...leftList] 克隆数组也无济于事。</p><p> 我迷路了:-)希望有人能对此有所了解吗?</p></div></object> - Cannot assign to read only property 'property' of object '#<Object>' 未捕获的TypeError:无法分配为只读对象&#39;#的属性&#39;background&#39; <Object> “ - Uncaught TypeError: Cannot assign to read only property 'background' of object '#<Object>' 未捕获的TypeError:无法分配给对象'#<Object>'的只读属性'exports' - Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' TypeError:无法分配为只读对象“#”的属性“ exports” <Object> 在ReactJS中 - TypeError: Cannot assign to read only property 'exports' of object '#<Object>' in ReactJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM