You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R ShinyDashboard点击ActionButton调用API时出现函数未找到错误

解决Shiny Dashboard中API调用函数未找到的错误

错误原因

你碰到的Error in api_firm_call: could not find function "api_firm_call"问题,核心是误用了observeEvent的作用。observeEvent是Shiny中的观察者组件,仅用于触发副作用(比如打印日志、修改外部变量),它不会返回任何值,也不能像普通函数那样通过api_firm_call()调用。而你需要的是一个能在按钮点击时生成并返回数据的反应式逻辑,应该用eventReactive替代。

修正后的完整代码

library(shiny)
library(shinydashboard)
library(httr)
library(jsonlite)
library(dplyr)

header <-  dashboardHeader()
sidebar <- dashboardSidebar(sidebarMenu(
  menuItem("New Entry", tabName = "new_entry_tab", icon = icon("stats-bars", lib = 'glyphicon'))
))
body <-  dashboardBody(
  tabItems(
    tabItem(tabName = "new_entry_tab",
            fluidPage(
              fluidRow(numericInput(inputId = "cvr", "Enter CVR number:",
                                   value = NULL,  # 修正:改为数值类型的默认值
                                   min = 1000000,
                                   max = 99999999,  # 修正:乐高CVR是8位,原max不够
                                   step = NA,
                                   width = NULL)), 
              fluidRow(actionButton("button_cvr", "Search")),
              fluidRow(box(tableOutput("firm_info")))
            )
    )
  )
)

ui <- dashboardPage(header, sidebar, body)

# Server ----
server <- function(input, output) {
  
  # 用eventReactive替代observeEvent,生成可返回数据的反应式对象
  api_firm_call <- eventReactive(input$button_cvr, {
    req(input$cvr)  # 确保CVR输入不为空时才执行
    cvr <- input$cvr
    firm_data <- GET(paste0("https://cvrapi.dk/api?search=", cvr, "&country=dk"))
    firm <- fromJSON(rawToChar(firm_data$content))
    
    # 构造表格数据
    firm_matrix <- matrix(ncol = 1, nrow = 5)
    rownames(firm_matrix) <- c("Name", "Address", "City", "Industry", "Industry Name")
    colnames(firm_matrix) <- " "
    firm_matrix[1:5, 1] <- c(
      firm$name, 
      firm$address, 
      paste(firm$zipcode, firm$city),
      firm$industrycode, 
      firm$industrydesc
    )
    as_tibble(firm_matrix, rownames = "Attribute")  # 修正:保留行名为表格列,更直观
  })

  # 渲染表格,调用反应式对象
  output$firm_info <- renderTable({
    api_firm_call()
  })
  
}

shinyApp(ui, server)

关键修改点说明

  1. 替换observeEvent为eventReactive:eventReactive专门用于创建依赖事件触发的反应式数据生成逻辑,会返回可调用的反应式对象,正好匹配你需要生成表格数据的场景。
  2. 修正numericInput参数:
    • 将value = "cvr"改为value = NULL,避免字符串类型输入导致的警告;
    • 调整max = 99999999,因为乐高的CVR号是8位,原最大值不够。
  3. 添加req(input$cvr):确保只有当用户输入了有效的CVR号后,才执行API调用,避免空值报错。
  4. 优化表格结构:将行名转为表格的Attribute列,让输出更清晰易读。

内容的提问来源于stack exchange,提问作者Bloxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:45:45