【问题标题】:Cannot set value to object property in Typescipt. Cannot set property 'ismain' of undefined无法在 Typescript 中为对象属性设置值。无法设置未定义的属性“主要”
【发布时间】:2020-03-06 10:15:00
【问题描述】:

在类中,我初始化了一个 Photo 类型的对象,该对象是一个带有一些属性的接口。然后我尝试使用数组过滤器来过滤照片。

过滤器返回照片数组的副本,但我指定了我想要哪张照片,所以我将有一个内部有 1 个索引的数组。然后,我尝试将对象内部的一个属性设置为 false,并出现“无法设置角度未定义的属性 'ismain'”。任何想法为什么?

这是我的代码。

setMainPhoto(photo: Photo) {
this.userService
  .setMainPhoto(this.authService.decodedToken.nameid, photo.id)
  .subscribe(
    () => {
      // We use the array filter method to filter the photos apart from the main photo
      // Filter returns a copy of the photos array. Filters out anything that it doesn`t match in the p
      this.currentMain = this.photos.filter(p => p.ismain === true)[0];

      this.currentMain.ismain = false;
      photo.ismain = true;
      this.alertify.success('Successfully set to profile picture');
    },
    error => {
      this.alertify.error('Photo could not be set as profile picture');
    }
  );
}

在上述方法中会发生错误。 下面是我的照片界面。

   export interface Photo {

  id: number;
  url: string;
  dateadded: Date;
  ismain: boolean;
  description: string;
}

错误

更新

问题已解决

来自服务器的响应需要与对象属性相匹配。所以我不得不更改属性接口以匹配从服务器返回的 JSON 对象。

【问题讨论】:

  • this.currentMain = this.photos.filter(p => p.ismain === true)[0] - 你确定你在过滤后的数组中有任何元素吗?在这行之后,this.currentMain 可能是 undefined。
  • 哪个语句在 photo-editor.ts 的第 115 行???
  • @VLAZ 现在它来了。来自服务器的 JSON 对象与接口参数不匹配

标签: javascript arrays json


【解决方案1】:

试试这个

setMainPhoto(photo: Photo) {
this.userService
  .setMainPhoto(this.authService.decodedToken.nameid, photo.id)
  .subscribe(
    () => {
      // We use the array filter method to filter the photos apart from the main photo
      // Filter returns a copy of the photos array. Filters out anything that it doesn`t match in the p
      this.currentMain = this.photos.filter(p => p.ismain === true)[0];
      if (this.currentMain) {
          this.currentMain.ismain = false;
          photo.ismain = true;
      this.alertify.success('Successfully set to profile picture'); }
    },
    error => {
      this.alertify.error('Photo could not be set as profile picture');
    }
  );
}

如果这有效,则过滤器不会返回任何内容。

【讨论】:

  • 嗨 Thanasi - 它是未定义的......虽然在照片列表中我有 4 条记录,其中一条是 ismain = true,这怎么可能不从照片列表?
【解决方案2】:

有趣,我以前也遇到过这个问题。 Typescript 对大小写非常严格,如果您不完全匹配 json 对象,它将无法工作,创建新属性等。

我发现在构建我的打字稿模型之前查看 json 返回很有帮助,以确保我匹配正在发送的对象。

【讨论】:

  • 同意..这样更好
猜你喜欢
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2022-10-30
  • 2023-02-10
  • 2019-07-04
相关资源
最近更新 更多