![](/img/trans.png)
[英]How do I call an Elixir function from a Phoenix LiveView heex template passing arguments with data from socket assigns?
[英]elixir phoenix liveview - passing user id through socket
在liveview
中,如何将用户数据从leex
传递到context
? 我有phx.gen.live
profiles
上下文,并且我想在每次用户创建新配置文件时将 user_id 添加到配置文件中。 我将 create_profile 代码更改为:
**profiles.ex (context)**
def create_profile(attrs \\ %{}, userid) do
attrs = Map.put(attrs, "user_id", userid)
%Profile{}
|> Profile.changeset(attrs)
|> Repo.insert()
end
我正在使用pow
,所以在正常的 phoenix 情况下,我会这样做:
user = Pow.Plug.current_user(conn) #<-- this is conn
Profiles.create_profile(profile_params, user.id)
但在liveview
中,它使用的是socket
而不是conn
。 所以我不确定如何 go 关于它。
有很多不同的方法可以做到这一点,但我将描述一个简单的方法。
conn
。 如果您使用 Pow,我还假设您有一个user_token
。 如果是这样,请执行以下操作:conn
|> put_session(:user_token, user_token)
live_helpers.ex
文件(或者如果你没有的话创建它)并像这样制作一个 function : def assign_defaults(session, socket) do
socket =
socket
|> assign_new(:current_user, fn ->
find_current_user(session)
end)
socket
end
live_helpers
中,写这个 function: defp find_current_user(session) do
with user_token when not is_nil(user_token) <- session["user_token"],
%User{} = user <- Accounts.get_user_by_session_token(user_token),
do: user
end
mount
function 中: def mount(_params, session, socket) do
socket =
assign_defaults(session, socket)
{:ok, socket}
end
然后您将可以访问session.assigns.current_user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.