R语言 如何从闪亮应用中的模块返回选定的输入?

fivyi3re  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(115)

目标

我在R中的一个闪亮的应用程序中有一个模块,我想根据来自数据库的选择呈现选定的输入。我想从这个模块返回所选的选择作为一个React。

可复制示例:

为什么运行应用程序时selected_choice总是NULL

selector_input_ui <- function(id) {
  ns <- NS(id)
  tagList(
    uiOutput(ns("selectoor"))
  )
  
}

selector_input_server <- function(id) {
  
  moduleServer(
    id,
    function(input, output, session) {
      
      res_list <- reactive({
        # code for creating a list from data in a database
        ## mock-up list:
        list("choice1", "choice2", "choice3")
      })
      
      output$selectoor <- renderUI({
        selectInput(inputId = "selected",
                    label = "Select",
                    choices = res_list())
      })
      
      return(
        reactive({
          input$selected
        })
      )
    }
  )
}


library(shiny)

ui <- fluidPage(
  selector_input_ui("menu"),
  verbatimTextOutput("printt")
)

server <- function(input, output, session) {
  selected_choice <- selector_input_server("menu")
  
  output$printt <- renderPrint({
    
    selected_choice()
  })
}

shinyApp(ui, server)
oaxa6hgo

oaxa6hgo1#

您在selectInput中缺少ns

selector_input_ui <- function(id) {
  ns <- NS(id)
  tagList(
    uiOutput(ns("selectoor"))
  )
  
}

selector_input_server <- function(id) {
  
  moduleServer(
    id,
    function(input, output, session) {
      ns <- session$ns
      res_list <- reactive({
        # code for creating a list from data in a database
        ## mock-up list:
        list("choice1", "choice2", "choice3")
      })
      
      output$selectoor <- renderUI({
        selectInput(inputId = ns("selected"),
                    label = "Select",
                    choices = res_list() #,
                    # selected = res_list()[[1]]
                    )
      })
      
      return(
        reactive({
          input$selected
        })
      )
    }
  )
}


library(shiny)

ui <- fluidPage(
  selector_input_ui("menu"),
  verbatimTextOutput("printt")
)

server <- function(input, output, session) {
  selected_choice <- selector_input_server("menu")
  
  output$printt <- renderPrint({
    
    selected_choice()
  })
}

shinyApp(ui, server)

相关问题