我有下面的类FileInfo
,它实现了IFileInfo
接口。该类定义了一个实例成员函数ext
和一个函数getExt()
。在我的组件中,我有一个名为openTempFolder()
的私有方法,它基本上是一个超文本传输协议调用,返回一个FileInfo
数组。我一直得到一个TypeError
,即getExt()
不是一个函数,并且ext
在调用它们时一直返回未定义
。我在这里做错了什么?
我正在发布相关代码,
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
});
});
}
}
HTTP调用的响应不会生成FileInfo类的对象,尽管您定义了httpService. getRequest()方法的参数化类型。响应实际上是一个数组,其中元素是明显没有getExt()方法的纯JavaScript对象。
看到这个问题。它包含一些修复它的建议。