【问题标题】:Modules in separated server.R and ui.R files单独的 server.R 和 ui.R 文件中的模块
【发布时间】:2020-01-20 15:03:40
【问题描述】:

是否可以在单独的 app.R、server.R 和 ui.R 文件中写下的 Shiny App 中创建模块?

我找到的所有示例都是一个 app.R 文件,其中包含嵌入式服务器和 ui 函数。请参阅example 1example 2!、示例 3!

(我从最后一个示例中获取了该测试的代码)。

我试图运行这个应用程序:

app.R

library(shiny)

# load module functions
source("hello_world.R")

# Run the application 
shinyApp(ui = ui, server = server)

ui.R

#ui.R

library(shiny)
#source("hello_world.R")
ui <- fluidPage(

  titlePanel("Using of Shiny modules"),

  fluidRow(
    # Call interface function of module "hello_world"
    hello_worldUI(id = "id_1")
  )

)

服务器.R

#server.R

library(shiny)
source("hello_world.R")


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

  # Call logic server function of module "hello_world"
  callModule(module = hello_world, id = "id_1")

}

# UPDATE! -> my Error comes from this line of code  in server.R file: 
#shinyApp(ui = ui, server = server) 
#Removing the line above solve the problem. 

hello_world.R

#module 1: hello_world

# Function for module UI
hello_worldUI <- function(id) {
    ns <- NS(id)

    fluidPage(
        fluidRow(
            column(2, textInput(ns("TI_username"), label = NULL, placeholder = "your name")),
            column(2, actionButton(ns("AB_hello"), label = "Hello !"))
        ),
        hr(),
        fluidRow(
            column(12, textOutput(ns("TO_Hello_user")))
        )
    )

}

# Function for module server logic
hello_world <- function(input, output, session) {

    # When user clicks on "Hello" button : Update reactive variable "name"
    name <- eventReactive(input$AB_hello, {
        return(input$TI_username)
    })

    # Show greetings
    output$TO_Hello_user <- renderText({
        if (name() %in% "") {
            return("Hello world !")
        } else {
            return(paste("Hello", name(), "!"))
        }
    })

}

但是我收到了这个错误:

警告:有效错误:找不到对象“ui”
52:力
51: uiHttpHandler
50:闪亮应用
force(ui) 中的错误:找不到对象 'ui'

【问题讨论】:

  • 我更新了答案,所以现在应该是正确的。

标签: r module shiny


【解决方案1】:

应用程序不知道uiserver 对象,除非您在同一文件中定义它们并且它们是在运行时生成的,或者您在shinyApp() 之前从外部文件显式调用它们。如下更改您的app.R,它应该可以工作:

library(shiny)

# load module functions
source("hw.R")
# load ui elements
source("ui.R")
# load server function
source("serv.R")

# Run the application 
shinyApp(ui = ui, server = server)

【讨论】:

猜你喜欢
  • 2017-02-01
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
  • 2017-03-06
  • 1970-01-01
相关资源
最近更新 更多