如何在Elm中获取window.location.href? [英] How can I get window.location.href in Elm?

查看:82
本文介绍了如何在Elm中获取window.location.href?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an index.html which contains my Elm app. The Elm app uses various GETs to an API served by the same server as the one that serves the index.html.

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

Rather than hardcode the URLs in my Elm code for the GETs, e.g.:

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

是否有一个函数返回 window.location.href 的值?

is there a function which returns the value of window.location.href?

我想做类似的事情:

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

通过这种方式,如果我将服务器移至某处否则,我将不需要更新Elm代码中的所有URL。

In this way, if I move my server to somewhere else I will not need to update all the urls in my Elm code.

推荐答案

elm-history 包中的 location 函数可实现此功能,但已弃用,对于 0.18 版本不存在。

There is elm-history package with the location function for this, but it's deprecated and doesn't exist for 0.18 version.

然后,您可能要使用 elm-navigation 包,并将当前位置明确存储在您的模型。

Then you might want to use elm-navigation package and explicitly store the current location in your model.

请查看此示例。可以通过以下方式创建具有导航功能的程序:

Please have a look at this example. A program with navigation can be created via:

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

UrlChange 这是一种消息,会在每次更改URL时触发,因此您可以对其进行处理并设置当前值位置:

UrlChange here is a type of message, which triggers on every url change, so you can process it and set the current location:

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

然后完全在任何可访问模型的地方获取 location.href

And then purely get the location.href wherever the model is accessible.

在提供的应用程序中,该位置为 view viewLocation model.location

In the provided application, this place is view: viewLocation model.location

在您的应用程序中,例如:

In your application, it's, for example, something like this:

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

这篇关于如何在Elm中获取window.location.href?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆