首页 > 解决方案 > 为什么我不能从 typescript 类的实例成员函数或方法中获取值?

问题描述

我有以下FileInfo实现IFileInfo接口的类。该类定义了一个实例成员函数ext和一个函数getExt()。在我的组件中,我有一个名为的私有方法openTempFolder(),它基本上是一个 http 调用,它返回一个FileInfo. 我不断得到一个TypeError不是getExt()函数的函数,并在调用它们时ext不断返回。Undefined我在这里做错了什么?

我正在发布相关代码,

export class FileInfo implements IFileInfo {
  constructor(
    public exists: boolean,
    public length: number,
    public physicalPath: string,
    public name: string,
    public lastModified: Date,
    public isDirectory: boolean,
    public ext: () => string,
  ) {
    this.exists = exists;
    this.length = length;
    this.physicalPath = physicalPath;
    this.name = name;
    this.lastModified = lastModified;
    this.isDirectory = isDirectory;
    this.ext = () => {
      return this.name.replace(/^.*\./, '');
    };
  }
  getExt() {
    return this.name.replace(/^.*\./, '');
  }
}

在我的组件中,我这样称呼,

export class FileManagerComponent implements OnInit, OnDestroy {
  @ViewChild('fileManager') public fileManager;
  public contents: Array<FileInfo> = new Array<FileInfo>();
  private unsubscribe: Subject<void> = new Subject();

....

 private openTempFolder() {
    this.httpService
      .getRequest<Array<FileInfo>>('FileManager/OpenTemporaryDirectory/Uploads')
      .subscribe((r: HttpResponse<Array<FileInfo>>) => {
        this.contents = r.body;
        this.contents.forEach(e => {
          console.log(e.getExt()); // TypeError
          console.log(e.ext()); // Undefined
        });
      });
  }
}

标签: angulartypescript

解决方案


尽管您定义了 httpService.getRequest() 方法的参数化类型,但 HTTP 调用的响应不会生成 FileInfo 类的对象。响应实际上是一个数组,其中元素是纯 JavaScript 对象,显然没有 getExt() 方法。

看到这个问题。它包含一些修复它的建议。


推荐阅读