打字稿类型BeforeInstallPromptEvent

时间:2018-07-24 16:44:01

标签: angular typescript service-worker progressive-web-apps

使用beforeinstallprompt事件时应该使用哪种类型?

我尝试过BeforeInstallPromptEvent类型,但是给了我一个错误:

export class PwaService {
  //promptEvent: BeforeInstallPromptEvent;
  promptEvent;
  constructor(private swUpdate: SwUpdate, platform: PlatformService) {
    if(platform.isBrowser()){
      swUpdate.available.subscribe(event =>  {
        /*if (askUserToUpdate()) {
          window.location.reload();
        }*/
      });
      window.addEventListener('beforeinstallprompt', event => {
        this.promptEvent = event;
      });
    }
  }

  install(): void {
    if(this.promptEvent){
      this.promptEvent.prompt();
    }
  }
}

2 个答案:

答案 0 :(得分:10)

BeforeInstallPromptEvent是非标准的Web API,目前仅受Chrome和Android支持。我什至不确定Google是否认为它稳定,但是无论哪种情况,我都不希望很快在TypeScript DOM库中看到正式的类型定义。

不过,您可以自己定义类型,例如在 .d.ts文件中。我使用下面的定义(来自MDN的注释),在Chrome 68中似乎足够准确。

/**
 * The BeforeInstallPromptEvent is fired at the Window.onbeforeinstallprompt handler
 * before a user is prompted to "install" a web site to a home screen on mobile.
 *
 * @deprecated Only supported on Chrome and Android Webview.
 */
interface BeforeInstallPromptEvent extends Event {

  /**
   * Returns an array of DOMString items containing the platforms on which the event was dispatched.
   * This is provided for user agents that want to present a choice of versions to the user such as,
   * for example, "web" or "play" which would allow the user to chose between a web version or
   * an Android version.
   */
  readonly platforms: Array<string>;

  /**
   * Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed".
   */
  readonly userChoice: Promise<{
    outcome: 'accepted' | 'dismissed',
    platform: string
  }>;

  /**
   * Allows a developer to show the install prompt at a time of their own choosing.
   * This method returns a Promise.
   */
  prompt(): Promise<void>;

}

答案 1 :(得分:1)

不要忘记您还需要在 WindowEventMap 中添加一个键:

interface BeforeInstallPromptEvent extends Event {
  readonly platforms: string[];
  readonly userChoice: Promise<{
    outcome: "accepted" | "dismissed";
    platform: string;
  }>;
  prompt(): Promise<void>;
}

declare global {
  interface WindowEventMap {
    beforeinstallprompt: BeforeInstallPromptEvent;
  }
}

window.addEventListener("beforeinstallprompt", (e) => {}); // e is now typed

请注意,declare global {} 是用于在代码中输入全局内容的包装器。如果您在不存在导入/导出关键字的环境 .d.ts 文件中执行此操作,则不需要包装器。