英文:
Using ContextApi in SvelteKit in +page.server.ts
问题
我有一个与外部API连接的SvelteKit
应用程序。用户打开我的网站后,我从外部API获取用户数据并将其保存在使用ContextAPI
包装的store中(参考https://kit.svelte.dev/docs/state-management#using-stores-with-context),但是当我尝试在+page.server.ts中使用getContext('user')
时,我收到一个错误:
Error: Function called outside component initialization
我的问题是:如何在+page.server.ts文件的加载函数中访问此数据?
英文:
I have a SvelteKit
application connected to external API. After user opens my website I fetch user data from external API and save it in store wrapped in ContextAPI
(based on https://kit.svelte.dev/docs/state-management#using-stores-with-context) but
when i try to use getContext('user')
in +page.server.ts I'm getting an error:
Error: Function called outside component initialization
My question is: How can I get access to this data on load function in +page.server.ts
file.
答案1
得分: 2
存储和上下文适用于页面和组件,您应该或不能在服务器上使用它们。
您可以做的是从 +layout.server.ts
文件中获取数据,通过事件对象的 parent
属性。
export const load: PageServerLoad = async e =>
{
const layoutData = await e.parent();
...
请注意,这通常是不必要的。页面将自动获取合并的布局和页面数据,因此只有在 load
函数本身需要访问时才会真正有用。
英文:
Stores and contexts are for pages and components, you should or cannot use them on the server.
What you can do, is get data from a +layout.server.ts
file, via the event object's parent
.
export const load: PageServerLoad = async e =>
{
const layoutData = await e.parent();
...
Note that this is generally not necessary. The page will get merged layout and page data automatically, so this really is only useful if the load
function itself needs access.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论