ProgramJavaScriptAltJSElmElmガイドコマンドとサブスクリプション > HTTP

HTTP

サンプルコード

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
-- Make a GET request to load a book called "Public Opinion"
--
-- Read how it works:
--   https://guide.elm-lang.org/effects/http.html
--
 
import Browser
import Html exposing (Html, text, pre)
import Http
 
 
 
-- MAIN
 
 
main =
  Browser.element
    { init = init
    , update = update
    , subscriptions = subscriptions
    , view = view
    }
 
 
 
-- MODEL
 
 
type Model
  = Failure
  | Loading
  | Success String
 
 
init : () -> (Model, Cmd Msg)
init _ =
  ( Loading
  , Http.get
      { url = "https://elm-lang.org/assets/public-opinion.txt"
      , expect = Http.expectString GotText
      }
  )
 
 
 
-- UPDATE
 
 
type Msg
  = GotText (Result Http.Error String)
 
 
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    GotText result ->
      case result of
        Ok fullText ->
          (Success fullText, Cmd.none)
 
        Err _ ->
          (Failure, Cmd.none)
 
 
 
-- SUBSCRIPTIONS
 
 
subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none
 
 
 
-- VIEW
 
 
view : Model -> Html Msg
view model =
  case model of
    Failure ->
      text "I was unable to load your book."
 
    Loading ->
      text "Loading..."
 
    Success fullText ->
      pre [] [ text fullText ]

パッと見、見事にサッパリ意味が分からない!
焦らずにじっくり学べば、後で意味が分かるようになるのかなー。(ちょっと不安)

Cmd

  • Elmのランタイムシステムに実行して欲しいことを指示するためのコマンド。
  • initとupdateからコマンドを発行できる。
  1
  2
  3
  4
  5
  6
  7
  8
init : () -> (Model, Cmd Msg)
init _ =
  ( Loading
  , Http.get
      { url = "https://elm-lang.org/assets/public-opinion.txt"
      , expect = Http.expectString GotText
      }
  )

上記のコード片の中で、

Http.expectString

の部分がCmdに該当している。

関数定義の型注釈を見ると、init関数の返り値は、(Model, Cmd Msg)となっており、Cmdとその引数であるMsgが返り値に含まれていることが分かる。

Sub

このプログラムにおけるもう一つの新しい部分はsubscription関数になります。
Modelの情報から判断して何らかの情報に対する待ち受けするかどうかを決めることができます。
今回の例ではSub.noneとして何も待ち受けする必要がないことを示していますが、後ほど現在時刻を待ち受ける必要がある時計の例を見ていきます。

  1
  2
  3
  4
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none

Elmのランタイムシステムに対して、処理やデータを渡したり、受け取ったりできる、ということですね?
何となく雰囲気はつかめました。


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019-11-23 (土) 21:25:04 (1615d)