Angular + webauthn =“导航器”类型中不存在属性“凭据”?

问题描述 投票:0回答:2

我一直在尝试将webauthn添加到Angular应用程序中。此MDN页面概述了必要的步骤:https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API

重要的是使用API​​需要访问navigator.credentials。但是,当我尝试引用它时,Angular不会编译。例如,这行代码:

await navigator.credentials.create({...});

...产生此错误:

error TS2339: Property 'credentials' does not exist on type 'Navigator'.

现在我知道我可以这样做:

declare global {
  interface Navigator {
    credentials: {
      create(): void,
      get(): void
    }
  }
}

但是,为整个CredentialsContainer API编写所有TypeScript是非常繁琐的。此外,有人已经在DefinitelyTyped做了所有工作,对吗?

所以我用@types/webappsec-credential-managementnpm install --save-dev @types/webappsec-credential-management添加到我的项目中。

现在,Visual Studio Code知道该怎么做;我有自动完成和一切。

但Angular仍然无法编译。它给出了同样的错误。

我需要做些什么才能让Angular识别出navigator.credentials

angular definitelytyped webauthn
2个回答
2
投票

您可以按以下步骤操作:

npm install --save-dev @types/webappsec-credential-management

然后编辑角度的<project>/src/tsconfig.app.json

{
  ...
  "compilerOptions": {
    ...
    "types": [
      "@types/webappsec-credential-management"
    ]
    ...
}

有必要编辑角度自己的tsconfig.app.json,因为它将用于编译角度代码。根tsconfig.json用于bootstrapping和general(vscode)typescript配置。因此,如果您只是将@types/webappsec-credential-management添加到您的类型中,它将在您的编辑器中被识别,但它将被angular自己的编译器忽略,从而创建此类型错误:

error TS2339: Property 'credentials' does not exist on type 'Navigator'.


0
投票

我在.ts文件的顶部错过了这个:

/// <reference types="@types/webappsec-credential-management" />

我还需要ng update typescriptng update @angular/cli

© www.soinside.com 2019 - 2024. All rights reserved.