我怎样才能在 Elm 中获得 window.location.href?
How can I get window.location.href in Elm?
我有一个 index.html
,其中包含我的 Elm 应用程序。 Elm 应用程序将各种 GET
用于 API,该 API 由与 index.html
.
服务的同一服务器提供服务
而不是在我的 Elm 代码中为 GET
硬编码 URL,例如:
url =
"http://localhost:8080/api/tasks"
是否有函数 returns window.location.href
的值?
我想做这样的事情:
url =
getHref() ++ "/api/tasks"
这样,如果我将我的服务器移动到其他地方,我将不需要更新我的 Elm 代码中的所有 url。
有 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"
虽然上面回答了你的问题,但我认为有一个更直接的解决方案:
如果应用程序代码是从与您要访问的 API 相同的服务器 (URL) 提供的,则无需指定服务器 - 只需指定根相对路径即可你的 api 即你可以从你的 elm 代码向 /api/tasks
发出请求,浏览器会为你解决剩下的问题。
这就是我在部署的代码中解决问题的方法。
使用 URL Builder link 到您网站上的另一个页面
无需指定基数url:
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 发生变化,您绝对无需担心。因此,您可以轻松地从开发环境切换到 production/staging 环境,无需任何额外配置。
我有一个 index.html
,其中包含我的 Elm 应用程序。 Elm 应用程序将各种 GET
用于 API,该 API 由与 index.html
.
而不是在我的 Elm 代码中为 GET
硬编码 URL,例如:
url =
"http://localhost:8080/api/tasks"
是否有函数 returns window.location.href
的值?
我想做这样的事情:
url =
getHref() ++ "/api/tasks"
这样,如果我将我的服务器移动到其他地方,我将不需要更新我的 Elm 代码中的所有 url。
有 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"
虽然上面回答了你的问题,但我认为有一个更直接的解决方案:
如果应用程序代码是从与您要访问的 API 相同的服务器 (URL) 提供的,则无需指定服务器 - 只需指定根相对路径即可你的 api 即你可以从你的 elm 代码向 /api/tasks
发出请求,浏览器会为你解决剩下的问题。
这就是我在部署的代码中解决问题的方法。
使用 URL Builder link 到您网站上的另一个页面
无需指定基数url:
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 发生变化,您绝对无需担心。因此,您可以轻松地从开发环境切换到 production/staging 环境,无需任何额外配置。