[英]Use assign from plug to view (elixir / phoenix)
我有我的api管道,我想在其中添加一个插件,该插件基本上在数据库中执行一些操作,并根据响应进行分配,然后在视图中使用该分配。
我在将分配从插件传递到视图时遇到问题。
网站/router.ex
pipeline :api do
plug ApiV2.Plug.Authenticate, repo: Auth.Repo
plug :accepts, ["json"]
end
web / controllers / auth.ex (仅分配)
defmodule ApiV2.Plug.Authenticate do
@behaviour Plug
import Plug.Conn
import Phoenix.Controller
def init(opts), do: opts
def call(conn, _opts) do
assign(conn, :current_user, 'user')
end
end
网站/控制器/address_controller.ex
defmodule ApiV2.AddressController do
use ApiV2.Web, :controller
alias ApiV2.Address
def index(conn, params) do
json conn, @current_user
end
end
我已经到了试图返回:current_user(我想)的地步,但是,由于assign是错误的,它只会返回
null
我想念什么?
谢谢
conn.assigns
映射中提供了使用assign
设置的值。 @current_user
是一个模块属性,由于未在此模块中设置,因此返回nil
。
这应该工作:
json conn, conn.assigns.current_user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.