无法获取组件内警报中的值

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

我正在 sveltekit 中开发一个 web 应用程序,但无法获取警报中的值(用于调试)。 我有一个组件 ModalFlight.svelte。我无法获取在 page.sever.ts 中检索到的令牌的值。 检索到的值是来自第三方 api 的令牌,我也希望其他组件可以使用该令牌。 我不想在这里使用 cookie,因为我想加深对哪里出错的理解

我能够在 page.server.ts 中获取该值 下面的代码适用于 ModalFlight.svelte,我没有看到警报中的值。

<script lang="ts">
    import my_store from '$lib/Store';
    import { get } from 'svelte/store';
    import { page } from '$app/stores';

    $: tokenString = '';
    my_store.subscribe((data) => {
        tokenString = get(my_store).token;
        console.log('subscribed value' + tokenString);
    });

    function fetchFlights() {
        alert(get(my_store).token);
    }
    
</script>

<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-noninteractive-element-interactions -->

    <!-- svelte-ignore a11y-no-static-element-interactions -->

    <div on:click|stopPropagation class="flightbar">
        
                <button class="btn" on:click={() => fetchFlights()}>Find Flights</button>
    </div>

 

page.server.ts 的代码:

import { amedeus_client_id } from '$env/static/private';
import { amedeus_secret } from '$env/static/private';
import $my_store from '$lib/Store'
import { get } from 'svelte/store';
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

const urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
urlencoded.append("client_id", amedeus_client_id);
urlencoded.append("client_secret", amedeus_secret);

function getToken():any{
    let data;
    const requestOptions = {
        method: "POST",
        headers: myHeaders,
        body: urlencoded,
        redirect: "follow"
      };
      
      fetch("https://test.api.amadeus.com/v1/security/oauth2/token", requestOptions)
        .then((response) => response.text())
        .then((result) => {
            const tokenDetails = JSON.parse(result); 
            data = tokenDetails;
            $my_store.set( {'token': tokenDetails.access_token});
            $my_store.update((data) => {
                return {'token': tokenDetails.access_token}
            });
            console.log('hello'+JSON.stringify(get($my_store)));
          //  console.log(JSON.stringify(token));
          //  token.set(tokenDetails.access_token);  
          //  console.log("printing result : "+token)
        })
        .catch((error) => console.error(error));
        return data;
}

export async function load() {
    return {
      posts:  getToken()
    }
  }
import {
  writable
} from 'svelte/store';

const my_store = writable({
  'token': 'default value'
});



my_store.set({
  'token': ''
});

export default my_store;

sveltekit
1个回答
0
投票

因此,我完全删除了商店解决方案,因为问题可能出在加载顺序上。我传递了页面数据中的值并使其正常工作。

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