Svelte 将异步脚本中的值存储在变量中

Svelte store value from async script in variable

我是 svelte 的新手,所以我可能遗漏了一些明显的东西。我想在我的 Svelte 应用程序中使用 OAuth2。没有 npm 包,所以,我需要使用常规 <script> 加载它。我想从 Google api 检索用户并将其显示在我组件的变量中。目前我正在将脚本加载到 <svelte:head> 组件中,这工作正常。这是我的工作代码:

<svelte:head>
  <script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
  <script>
    function init() {
      gapi.load("auth2", function () {
        gapi.auth2
          .init({
            clientId: "my_clientId",
            apiKey: "my_apiKey",
          })
          .then(() => {
            GoogleAuth = gapi.auth2.getAuthInstance(); // Create instance
            if (GoogleAuth.isSignedIn.get()) { // If signed in, log name
              const profile = GoogleAuth.currentUser.get().getBasicProfile();
              console.log("Full Name: " + profile.getName());
            } else { // Else trigger login
              GoogleAuth.signIn();
            }
          });
      });
    }
  </script>
</svelte:head>

如果用户已登录,此代码将 console.log 用户名,否则会触发 google 登录弹出窗口。

我如何将从 GoogleAuth 检索到的用户配置文件存储在我的 Svelte 组件的变量中,而不是仅仅记录它?我试过了 these suggestions and also tried to pass an on:load={} function to my svelte:head> as shown here.

<script> 块中包含 init 函数

<script>

window.gauthinit = ()=>{
 gapi.load("auth2", function () {
        gapi.auth2
          .init({
            clientId: "my_clientId",
            apiKey: "my_apiKey",
          })
          .then(() => {
            GoogleAuth = gapi.auth2.getAuthInstance(); // Create instance
            if (GoogleAuth.isSignedIn.get()) { // If signed in, log name
              const profile = GoogleAuth.currentUser.get().getBasicProfile();
              console.log("Full Name: " + profile.getName());

              ////DO SAVE DATA IN STORES
 
            } else { // Else trigger login
              GoogleAuth.signIn();
            }
          });
      });

}

</script>

<svelte:head>中更改为

<svelte:head>
  <script
    src="https://apis.google.com/js/platform.js?onload=gauthinit"
    async
    defer>

  </script>
</svelte:head>

要在加载 <svelte:head> 中的脚本后调用函数,可以使用 on:load 调用函数。确保用括号调用此函数,如下所示:on:load="{yourFunction()}" 而不是 on:load="{yourFunction}"(这是我做错的地方)。

最终代码如下所示:

<script>
  function init() {
    gapi.load("auth2", function () {
      gapi.auth2
        .init({
          clientId: process.env.GOOGLE_CLIENT_ID,
          apiKey: process.env.GOOGLE_API_KEY,
        })
        .then(() => {
          const GoogleAuth = gapi.auth2.getAuthInstance();
          if (!GoogleAuth.isSignedIn.get()) {
            if (window.location.pathname !== "/login") {
              window.location.href = "/login";
            }
          }
        });
    });
  }
</script>

<svelte:head>
  <script
    src="https://apis.google.com/js/platform.js"
    async
    defer
    on:load="{init()}">
  </script>
</svelte:head>

init 函数现在位于常规脚本标记中。我们也可以从这里访问 svelte 商店。