如何通过Elm端口传递联合类型?

时间:2016-06-23 18:46:30

标签: json elm

我在尝试榆树时碰到了一个问题。我想通过端口传递一个union类型,但是我收到了这个错误:

Port `setStorage` is trying to communicate an unsupported type.

34| port setStorage : Model -> Cmd msg
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The specific unsupported type is:

    Todo.Importance

The types of values that can flow through in and out of Elm include:

    Ints, Floats, Bools, Strings, Maybes, Lists, Arrays,
    Tuples, Json.Values, and concrete records.

我修改了Todo example,如下所示:

type alias Task =
    { description : String
    , completed : Bool
    , editing : Bool
    , id : Int
    , importance : Importance -- <- this is the new field
    }

type Importance
  = Normal
  | High
  | Low

issue似乎很老了。一位评论者建议“通过端口传递Json.Values和Json.Decode / Encode”但是如何做到这一点?文档似乎有点不清楚,缺乏完整的例子。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:8)

我用Json.Decoder / Encoder创建了work。毕竟不是那么困难,虽然必须序列化每一个字段只是为了通过一个联合类型是一个相当大的负担。

解码器:

update [promotion]
set DateStart = '2016.06.24 08:00:00', 
    DateEnd = '2017.07.10 10:00:00',
    TimeStart1 = '2016.06.24 18:00:00',
    TimeEnd1 = '2017.10.10 12:00:00',
    TimeStart2 = '2016.10.02 411:00:00',
    TimeEnd2 = '2017.12.25 15:00:00'
where PromotionName='40%Off';

编码器:

public function index(){


    $url = "https://www.googleapis.com/webfonts/v1/webfonts?key=!";
    $result = json_decode(file_get_contents( $url ));
    $font_list = "";
    foreach ( $result->items as $font )
    {
        $font_list[] = [
            'font_name' => $font->family,
            'category' => $font->category,
            'variants' => implode(', ', $font->variants),
            // subsets
            // version
            // files
        ];
    }

    return view('website_settings')->with('data', $font_list);

}

答案 1 :(得分:3)

你不能首先传递一个联合类型,因为JS不知道这样的事情。所以你不妨传递一个字符串并在javascript中做一个case语句 - 我会一直这样做。