Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir Plug.Conn.assign在从管道插头调用时不工作_Elixir_Phoenix Framework - Fatal编程技术网

Elixir Plug.Conn.assign在从管道插头调用时不工作

Elixir Plug.Conn.assign在从管道插头调用时不工作,elixir,phoenix-framework,Elixir,Phoenix Framework,我按照创建自己的模块插件,从会话加载当前用户。当使用插件模块时,@user没有被分配,但是当我在router.ex中将其作为私有函数调用时,它可以正常工作 这是我的网络/路由器: defmodule MyApp.Router do use MyApp.Web, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :p

我按照创建自己的
模块插件
,从会话加载当前用户。当使用插件模块时,
@user
没有被分配,但是当我在
router.ex中将其作为私有函数调用时,它可以正常工作

这是我的
网络/路由器

defmodule MyApp.Router do
  use MyApp.Web, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug MyApp.Plugs.User
  end

  # Scopes and Routes...

end
这是我的模块(在
web/plugs/user.ex
中):

我试着检查它,看它是否真的被分配了,但它不是:

%Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...}, assigns: %{},
 before_send: [#Function<1.75757453/1 in Plug.CSRFProtection.call/2>,
  #Function<1.30521811/1 in Phoenix.Controller.fetch_flash/2>,
  #Function<0.39713025/1 in Plug.Session.before_send/2>,
  #Function<1.7608073/1 in Plug.Logger.call/2>,
  #Function<0.72065156/1 in Phoenix.LiveReloader.before_send_inject_reloader/1>],
 body_params: %{},
 cookies: ....
%Plug.Conn{adapter:{Plug.Adapters.Cowboy.Conn,:…},赋值:%{},
发送前:[函数,
#功能,
#功能,
#功能,
#功能],
正文参数:%{},
饼干:。。。。

Plug.Conn.assign
返回一个修改过的连接。由于Elixir中的所有数据都是不可变的,因此不可能修改旧连接。在您的情况下,您正在丢弃
assign
的结果,而Conn仍然指向旧连接。您可能需要类似以下内容:

conn = assign(conn, :user, user)

这将重新绑定
conn
变量以指向修改后的连接结构。当然,如果
assign(conn,:user,user),它也会起作用
将是函数中的最后一个表达式,因为它的结果将被返回。

我明白了……我想我应该在转到Phoenix之前获得我的长生不老药基础知识。还要注意,
IO.inspect
返回它检查的值,因此
assign(conn,:user,user)|>IO.inspect
也会起作用
conn = assign(conn, :user, user)