angular - 为什么我不能从 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
});
});
}
}
解决方案
尽管您定义了 httpService.getRequest() 方法的参数化类型,但 HTTP 调用的响应不会生成 FileInfo 类的对象。响应实际上是一个数组,其中元素是纯 JavaScript 对象,显然没有 getExt() 方法。
看到这个问题。它包含一些修复它的建议。
推荐阅读
- java - 连接时在 AWS API 网关 websocket api 中收到的 Java 对象
- wordpress - Wordpress 智能滑块插件不起作用
- reactjs - React Hooks:useState with onClick 仅在第二次单击按钮后更新?
- python - Python使用关键字提取html网页内容
- android - RecyclerView 滚动慢 - setHasStableIds 不起作用,可以预加载多个屏幕外视图?
- sql - 自定义运行和查询
- ios - Pod 安装 Firebase/Analytics 失败
- java - 从 .eml 文件中获取文本的最佳方法是什么?
- android - 如何让我的列表视图在新的活动类中工作
- html - 为什么div在另一个div里面?