让 downloadButton 与 observeEvent 一起使用

Car*_*lla 7 r shiny

我想添加功能,一旦用户downloadButton在我闪亮的应用程序中点击,就会给予用户反馈(例如,它会给用户一条警告消息或在点击后切换 ui 元素)。本质上,我希望能够downloadButton下载一些数据表现得像actionButton,以便它响应事件触发器。这可能吗?这是我设置代码的方式:

ui <- fluidPage(
  useShinyjs(),

  downloadButton("download", "Download some data")
)

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

  observeEvent(input$download, {  # supposed to alert user when button is clicked
    shinyjs::alert("File downloaded!")  # this doesn't work
  })

  output$download <- downloadHandler(  # downloads data
    filename = function() {
      paste(input$dataset, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(mtcars, file, row.names = FALSE)
    }
  )

}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

这似乎只有在我更改downloadButtonactionButtonui 中的元素时才有效,但这样做会禁用下载输出。

div*_*san 7

这有点像黑客,但你可以让downloadHandler函数修改一个reactiveValue,它充当一个标志来触发观察事件:

# Create reactiveValues object
#  and set flag to 0 to prevent errors with adding NULL
rv <- reactiveValues(download_flag = 0)

# Trigger the oberveEvent whenever the value of rv$download_flag changes
# ignoreInit = TRUE keeps it from being triggered when the value is first set to 0
observeEvent(rv$download_flag, {
    shinyjs::alert("File downloaded!")
}, ignoreInit = TRUE)

output$download <- downloadHandler(  # downloads data
    filename = function() {
        paste(input$dataset, ".csv", sep = "")
    },
    content = function(file) {
        write.csv(mtcars, file, row.names = FALSE)
        # When the downloadHandler function runs, increment rv$download_flag
        rv$download_flag <- rv$download_flag + 1
    }
)
Run Code Online (Sandbox Code Playgroud)