如何在 angular worker 中使用 requestFileSystemSync API?

How to use requestFileSystemSync API in angular worker?

在常规 JavaScript worker 中,我可以使用 requestFileSystemSync 文件系统 API,如下所示。

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

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

感谢您的帮助。

Angular 工人实际上是通常的(网络)工人,但你需要用打字稿写他们。你的问题是编译打字稿文件引起的。

因为 FileSystemSync API (MDN) 实验性的 并且 已弃用 它泄漏了类型声明。这意味着 TS 编译器不知道它们存在于您的环境中(chrome/chromium/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);