在下面的代码片段中,我使用服务(Angular)通过fileReader提取文本,使用异步部分的promise。我遇到的问题是(我相信)一个范围问题,我对此感到困惑。在我的组件中,我声明了一个实例变量:myDoc:docWrapperClass。
基本上,当文件阅读器提取文本时,我想将结果分配给此局部变量。一切顺利,直到我尝试完成任务。即:当承诺结算时(this.myDoc = docContents)(目前已注释掉)。
当语句留在编译器中时抱怨:类型'{}'不能赋值为docWrapperClass:fileName。
docWrapperClass上有一个名为fileName的属性,但不确定{}的含义。我已经注释掉了赋值,然后在then()块中的console.log语句中放置了一个断点。当我在控制台中键入“this”时,我得到了未定义,这真让我困惑。我至少期望“这个”成为一个功能。我的问题是如何将promise中返回的docWrapperClass分配给实例变量?
export class myDocComponent implements OnInit {
constructor(private fileReaderService: ReadLocalFileService,
private textExtractor: TextExtractorServiceService) { }
ngOnInit() { }
docWords: string[] = [];
myDoc: docWrapperClass = null;
selectFile(event: any) {
console.log("Debug");
this.fileReaderService.readFile(event.target.files)
.then((docContents) => {
console.log("DocContents: " + docContents);
//this.myDoc = docContents;
});
}
}
this.fileReaderService.readFile
没有返回签名,所以当你在它的返回值上调用then
时,Typescript编译器不知道它正在使用什么。因此,你的docContents
是{}
类型,不能分配给你的docWrapperClass
类型。
TypeScript的一大优势是类型安全。您应该将readFile
的返回类型定义为Promise<docWrapperClass>
,同样定义所有函数的返回类型。
一旦编译器意识到该方法返回Promise<docWrapperClass
,它就可以正确推断docContents
可以赋值给myDoc
。