如何将插件加载的数据传递到LiveView组件 [英] How to pass plug loaded data to LiveView components
问题描述
我正在使用不同的域名来加载不同的数据集.我目前正在使用自定义插件根据主机名加载正确的域ID.例如.在路由器之前将其保存在我的 endpoint.ex
中:
Hi I'm using different domain names to load different data sets. I'm currently using a custom plug to load the correct domain id based on the hostname. E.g. got this in my endpoint.ex
just before the router:
plug WebApp.DomainCheck
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
...
plug WebApp.Router
还有
defmodule WebApp.DomainCheck do
import Plug.Conn
@behaviour Plug
def init([]), do: []
def call(conn, _options \\ []) do
domains = Model.load_allowed_domains()
case Map.get(domains, conn.host) do
nil ->
conn
|> resp(401, "Domain not allowed")
|> halt()
domain_id ->
conn
|> assign(:domain_id, domain_id)
end
end
end
现在,这适用于普通的 View
,因为我在每个代码中都分配了 domain_id
.但是,如何通过插件将 domain
数据也注入到 LiveView
中呢?
Now this works for normal View
as I have the domain_id
assign in each of them. But how do I get the domain
data injected into my LiveView
s as well from a plug?
当前,我已经将代码复制了同一域检查到每个LiveViews mount()页面:
Currently I've code duplicated the same domain check into every LiveViews mount() page:
defmodule WebApp.WelcomeLive do
use WebApp, :live_view
@impl true
def mount(_args, _session, socket) do
domains = Model.load_allowed_domains()
host = socket.host_uri.host
case Map.get(domains, host) do
nil -> {:error, "Domain not allowed"}
domain_id -> {:ok, assign(socket, :domain_id, domain_id)}
end
end
有什么方法可以使我的插件有效地将数据向下推送到实时视图,而无需在每个安装中添加代码?
Is there any way I can make a plug effective in pushing this data down to the live views without need to add code to each mount?
推荐答案
我的应用程序中有一个类似的用例,其中我的插件将 user
结构放在 assigns
,我想将这些数据保留在实时视图中,而无需重新加载所有内容.
I had a similar use case in my app where my plug puts the a user
struct on the assigns
and I wanted to keep that data inside live view without reloading all stuff.
我能实现的唯一方法是使用选项来自 live
路由的a> session
,并将其传递给MFA.
The only way I could achieve that was using the option session
from the live
route passing it a MFA.
在路由器中,您将拥有类似的东西
In the router you will have something like
live "/page", WebApp.SomeLiveView, :show, session: {WebAppp.Helpers, :keep_domain_id, []}
和您的 WebApp.Helpers
将具有该函数,该函数将要作为 session
传递给实时视图的内容返回.
and your WebApp.Helpers
will have that function returning what you want to be passed to your live view as session
.
defmodule WebApp.Helpers do
def keep_domain_id(conn) do
%{"domain_id" => conn.assigns.domain_id}
end
end
然后在 mount
上的 session
defmodule WebApp.WelcomeLive do
use WebApp, :live_view
@impl true
def mount(_args, %{"domain_id" => domain} = _session, socket) do
...
end
end
这篇关于如何将插件加载的数据传递到LiveView组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!