【问题标题】:Svelte store value from async script in variableSvelte 将来自异步脚本的值存储在变量中
【发布时间】:2020-12-10 11:14:32
【问题描述】:

我是苗条的新手,所以也许我遗漏了一些明显的东西。我想在我的 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 用户名,否则将触发谷歌登录弹出窗口。

如何将从 GoogleAuth 检索到的用户配置文件存储在我的 Svelte 组件中的变量中,而不是仅仅记录它?我尝试过these suggestions,还尝试将on:load={} 函数传递给我的svelte:head&gt;,如here 所示。

【问题讨论】:

  • 您是否尝试过使用svelte store?您可以存储用户配置文件,然后以反应方式将其再次获取到另一个文件中。
  • @johannchopin 这正是我想做的。但是我现在使用的函数在&lt;svelte:head&gt; 中。我认为我无法从 svelte:head&gt; 中访问商店。
  • 是的,你是对的,实际上它不起作用。但实际上将这个函数放在head 中的目标是什么?
  • @johannchopin 我需要先等待 gapi 包加载。加载后,我可以验证当前用户。我可以等待包加载然后验证用户的唯一方法是将函数放在头部,然后在加载时调用 init 函数。如果有一种方法可以做到这一点而不将函数放在head 中,那很好。
  • 当然你可以在你的 entry svelte 组件的 Mount 上做到这一点。在执行其他所有操作之前,请等待此功能。

标签: javascript oauth-2.0 svelte


【解决方案1】:

&lt;script&gt; 块内包含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>

&lt;svelte:head&gt;改成这个

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

  </script>
</svelte:head>

【讨论】:

  • 这行得通!我确实必须将该函数放在onMount 中,但它工作正常!谢谢!
  • 所以,我认为这行得通。但我想浏览器中缓存了一些东西,使它工作。如果我将代码放在&lt;script&gt; 标记中,它会运行,但我收到错误window is undefined。我尝试将其移至onMount,但该功能根本没有运行。
【解决方案2】:

要在&lt;svelte:head&gt; 中的脚本加载后调用函数,可以使用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 函数现在位于常规脚本标记中。我们也可以从这里访问苗条的商店。

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2018-01-31
    • 2015-08-06
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多