1

我有一个使用config包的闪亮应用程序,根据应用程序环境(测试/质量保证/生产环境)使用不同的配置。

由于我也在为应用程序使用 JS 文件,我想知道是否可以从config.yamlJS 文件中的文件中获取值?

现在我已经硬编码了我需要的值。

在这个小例子中,我想将val配置文件中的值传递给 JavaScript,这样在部署到某个环境时我不必手动更改该值。在我想要访问的 js 部分的app.Rconfig$val文件中,而不是像硬编码这样的值var val = "abcdef"

配置.yaml

default:
  val: 'default123'
qa:
  val: 'qa123'
prod:
  val: 'prod123'

应用程序.R

sys <- Sys.info()
ifelse("Windows" %in% sys[1],
       {Sys.setenv(R_CONFIG_ACTIVE = "default")},
       {ip <- system("ip address | grep -A 1 'eth0'  | tail -2", intern = TRUE)
       ip <- gsub(pattern = "inet ", "", regmatches(ip, regexpr("inet [0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+", ip)), fixed = T)
       ifelse(ip == "prodip",
              Sys.setenv(R_CONFIG_ACTIVE = "prod"),
              Sys.setenv(R_CONFIG_ACTIVE = "qasys"))
       })

js <- HTML('
$(document).on("shiny:connected", function (event) {
  // How can i access values from the config file in here?
  //var val = config$val;  // I wanna do this line, rather than 
  var val = "default123";      // this line
  console.log(val);
})           
')

library(shiny)

ui <- fluidPage(
  tags$head(tags$script(js))
)

server <- function(input, output, session) {}

shinyApp(ui, server)
4

1 回答 1

1

有趣的问题(+1)。您可以将数据读入 R,然后用于Shiny.addCustomMessageHandler(...)将数据从 R 传递到 javascript。

在服务器端,您将使用:

  observeEvent(input$showAlert,{
    message = config$default$val
    session$sendCustomMessage("handler1", message)
  })                     

在javascript中:

Shiny.addCustomMessageHandler("handler1", showConfig );
function showConfig(message){
   alert(message);
}

可重现的例子:

library(yaml)
library(shiny)
config = read_yaml("config.yaml")

ui = shinyUI(
  bootstrapPage(
    tags$script('
                Shiny.addCustomMessageHandler("handler1", showConfig );
                function showConfig(message){
                  alert(message);
                }
    '),
    actionButton("showAlert", "show alert")
  )
)

server = shinyServer(function(input,output,session){
  observeEvent(input$showAlert,{
    message = config$default$val
    session$sendCustomMessage("handler1", message)
  })                     
})

shinyApp(ui, server)
于 2019-06-17T21:03:11.017 回答