【问题标题】:How can I get window.location.href in Elm?如何在 Elm 中获取 window.location.href?
【发布时间】:2019-01-10 19:35:21
【问题描述】:

我有一个 index.html,其中包含我的 Elm 应用程序。 Elm 应用程序使用各种 GETs 到一个 API,该 API 由与 index.html 提供服务的服务器相同。

而不是在我的 Elm 代码中为 GETs 硬编码 URL,例如:

url =
    "http://localhost:8080/api/tasks"

有没有返回window.location.href值的函数?

我想做这样的事情:

url =
    getHref() ++ "/api/tasks"

这样,如果我将服务器移动到其他地方,我就不需要更新 Elm 代码中的所有 url。

【问题讨论】:

    标签: elm location-href


    【解决方案1】:

    elm-history 包与location 功能为此,但它已被弃用并且不存在0.18 版本。

    那么您可能想要使用elm-navigation 包并将当前位置显式存储在您的模型中。

    请查看this example。可以通过以下方式创建带导航的程序:

    Navigation.program UrlChange
        { init = init
        , view = view
        , update = update
        , subscriptions = (\_ -> Sub.none)
        }
    

    UrlChange这里是一种消息,每次url变化都会触发,所以你可以处理它并设置当前位置:

    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            UrlChange location ->
                ( { model | location = location }
                , Cmd.none
                )
    

    然后纯粹在可以访问模型的任何地方获取location.href

    在提供的应用程序中,这个地方是view:viewLocation model.location

    在您的应用程序中,例如,它是这样的:

    url model =
        model.location.href ++ "/api/tasks"
    

    【讨论】:

      【解决方案2】:

      虽然以上回答了您的问题,但我认为有一个更直接的解决方案:

      如果应用程序代码与您要访问的 API 从同一服务器 (URL) 提供服务,则无需指定服务器 - 只需指定 api 的根相对路径即可,即您可以向 @987654321 发出请求@ 来自您的 elm 代码,浏览器将为您整理其余部分。

      这就是我在部署的代码中解决问题的方式。

      【讨论】:

        【解决方案3】:

        使用 URL Builder 链接到您网站上的另一个页面

        无需指定基本网址:

        import Url.Builder exposing (absolute)
        url = absolute [ "api", "tasks" ] []
        -- results in "http://localhost:8080/api/tasks"
        -- if working in your developer environment
        -- the URL will automatically change in production
        -- to the correct URL assuming you don't have any crazy set ups
        

        如果您的服务器 URL 发生变化,您绝对不必担心。因此,您无需任何额外配置即可轻松地从开发环境切换到生产/暂存环境。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-10
          • 2017-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-09
          相关资源
          最近更新 更多