如何在angular worker中使用requestFileSystemSync API



在普通的JavaScript工作者中,我可以使用requestFileSystemSync文件系统API,如下所示。

self.requestFileSystemSync = self.webkitRequestFileSystemSync || self.requestFileSystemSync;
var fs = requestFileSystemSync(PERSISTENT, 1024);

如何在angular worker(.ts(文件中使用它?

感谢你的帮助。

角度工作者实际上是普通的(web(工作者,但您需要用typescript编写它们。您的问题只是由于typescript文件的编译造成的。

由于FileSystemSyncAPI(MDN(是实验性不推荐使用,因此它泄漏了打字声明。这意味着TS编译器不知道它们存在于您的环境中(chrome/chrom/webkit浏览器(,也不知道它是如何工作的。

为此,您需要指示编译器和declare您在浏览器中已经拥有的内容:

// constant declarations
declare const TEMPORARY: 0;
declare const PERSISTENT: 1;
// this is the object returned by requestFileSystemSync
interface FileSystemSync {
readonly name: string,
readonly root: FileSystemDirectoryEntry
}
// we tell to the compiler to add these two
// properties to the type definition
// of the global window object
//
// NOTE: self is a variable of type (Window & typeof globalThis)
//       and we extend the Window interface with the following
interface Window {
requestFileSystemSync: (type: 0 | 1, size: number) => FileSystemSync;
webkitRequestFileSystemSync?: (type: 0 | 1, size: number) => FileSystemSync;
}
// polyfill assignment
self.requestFileSystemSync = self.webkitRequestFileSystemSync ||
self.requestFileSystemSync;
// usage
var fs: FileSystemSync = self.requestFileSystemSync(PERSISTENT, 1024);

另一种处理未声明变量(我在评论中提到的那个(的方法是假设self全局对象是any类型的,这样编译器就不会抱怨我们如何管理它。这种方法通常是要避免的,因为任何人都可能拼写错误或使用错误,随后很难调试运行时错误:

(self as any).requestFileSystemSync = (self as any).webkitRequestFileSystemSync ||
(self as any).requestFileSystemSync;
// NOTE: PERSISTENT is not declared so use 1, the actual value
var fs = (self as any).requestFileSystemSync(1, 1024);
// OR you can access the global object again:
var fs = (self as any).requestFileSystemSync((self as any).PERSISTENT, 1024);
// Another way is to declare new constants
const TEMPORARY: 0 = 0;
const TEMPORARY: 0 = (self as any).TEMPORARY;
const PERSISTENT: 1 = 1;
const PERSISTENT: 1 = (self as any).PERSISTENT;
// Another way is to use the angle brackets:
(<any>self).requestFileSystemSync = (<any>self).webkitRequestFileSystemSync ||
(<any>self).requestFileSystemSync;
var fs = (<any>self).requestFileSystemSync(PERSISTENT, 1024);

最新更新