English 中文(简体)
当地储存具有初步价值的Svelte仓库
原标题:Typed Svelte store with initial value from local storage

我试图在我的SvelteKit SPA中实施JWT认证。 I m new to TS (and, Svelte[Kit]),有很多东西可以学习,因此,我的问题可能不是严格地与Svelte及其储存系统,而是与一般的TS。

我的所有需要认证的路线的<代码>+layout.svelte就座:

<script lang="ts">
    import { goto } from  $app/navigation ;
    import auth from  $lib/stores/auth ;
</script>

{#await auth.init() then user}
    <slot />
{:catch}
    {goto( /login )}
{/await}

www.un.org/Depts/DGACM/index_spanish.htm

import { writable, get } from  svelte/store ;
import { jwtDecode, type JwtPayload } from  jwt-decode ;

type User = {
    email: string;
    name: string;
};

interface Token extends JwtPayload {
    user: User;
}

function createStore() {
    const user = {};
    const { subscribe, update, set } = writable(user as User);

    return {
        subscribe,

        async init() {
            const tokenStr = localStorage.getItem( token )!;
            const token = jwtDecode<Token>(tokenStr);
            set(token.user);
        },

        setToken(tokenStr: string) {
            const token = jwtDecode<Token>(tokenStr);
            let storeValue = get(this);

            storeValue = token.user;

            update(() => storeValue);

            localStorage.setItem( token , tokenStr);
        }
    };
}

export default createStore();

我的问题是,我可以不使用<条码>用户在我的布局中产生目标(例如,在导航中显示用户名称等)。 它没有定义。 为什么如此?

问题回答

<代码>+layout.svelte 档案是能够使服务器和客户都能够查阅的组成部分。 页: 1 因此,试图在+layout内部接触当地Storage。 服务器-侧投放过程中的滚动文档将使用户成为<条码>未定义的<<>。

排外文件,使用

export const ssr = false;




相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Remotely authenticating client Windows user on demand

Suppose I am writing a server for a particular network protocol. If I know that the client is running on a Windows machine, is it possible for my server to authenticate the Windows user that owns the ...

Role/Permission based forms authorizing/authentication?

While looking into forms authorizing/authentication, I found that it is possible to do role based authorizing by adding an array of roles to a FormsAuthenticationTicket. That way I can write User....

热门标签