将Msg案例值作为泛型传递给执行Http.Post的另一个函数?

时间:2017-08-21 23:43:55

标签: elm

我正在尝试执行以下操作:

   Submit ->
        ( model, runtime.tryRegister model Response )

其中Response定义为:

| Response (Result Http.Error JsonProfile)

但是,以下函数无法编译:

tryRegister : Form -> (Result Http.Error a -> msg) -> Cmd msg
tryRegister form msg =
    let
        registerUrl =
            "http://localhost:5000/register"

        body =
            encode form |> Http.jsonBody

        request =
            Http.post registerUrl body decoder
    in
        Http.send msg request

错误:

Http.send msg request
  

函数send的第二个参数导致不匹配。 - 功能   send期待第二个参数为:

Http.Request a
     

但它是:

Http.Request JsonProfile

这是解码器:

decoder : Decoder JsonProfile
decoder =
    Decode.map4 JsonProfile
        (field "Id" Decode.int)
        (field "FirstName" Decode.string)
        (field "LastName" Decode.string)
        (field "Email" Decode.string)

source code can be found on GitHub

1 个答案:

答案 0 :(得分:2)

如果您试图保持tryRegister功能通用,因为您不希望它与JsonProfile绑定,那么您需要将解码器作为参数传递,而不是引用键入decoder的顶级函数JsonProfile

tryRegister : Form -> Decoder a -> (Result Http.Error a -> msg) -> Cmd msg
tryRegister form decoder msg =
    let
        registerUrl =
            "http://localhost:5000/register"

        body =
            encode form |> Http.jsonBody

        request =
            Http.post registerUrl body decoder
    in
        Http.send msg request

然后您可以在此处传递顶级decoder函数:

Submit ->
    ( model, runtime.tryRegister model decoder Response )