出现“Chart.JS错误:Microsoft.JSInterop.JSException:无法找到'setup'('setup'未定义)”我的chart.js的Blazor服务器应用程序出错

rsl1atfo  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(271)

我有一个Blazor服务器应用程序,在那里我使用chart.js库创建了一个饼图。
“Chart.JS错误:Microsoft.JSInterop.JSException:找不到'setup'('setup'未定义)”
我在谷歌上搜索了很多,我想也许安装程序在定义之前就被调用了。它是在我添加的项目中的“chart.js”中定义的。我不知道我是否在_host.cshtml中没有正确地调用它,或者在我的项目中没有正确地放置它。
这里我的代码:
_Host.cshtml(body部分的相关部分。我在给定路径中有所有的js文件。第一行chart.js在我的项目中,我在那里定义了window.setup)

  1. <script src="chart.js"></script>
  2. <script src="files/js/chart.js"></script>
  3. <script src="files/js/chart.min.js"></script>
  4. <script src="files/js/bootstrap.min.js"></script>
  5. <script src="files/js/helpers.esm.js"></script>
  6. <script src="files/js/jquery.slim.min.js"></script>
  7. <script src="files/js/popper.min.js"></script>
  8. <script src="files/js/helpers.mjs"></script>
  9. <script src="files/js/chart.mjs"></script>

项目中的chart.js

  1. window.setup = (id, config) => {
  2. var ctx = document.getElementById(id).getContext('2d');
  3. new Chart(ctx, config);
  4. }

图表所在的剃刀页

  1. @page "/wmi_performance2"
  2. @inject TagService TagService
  3. @using System.IO
  4. @inject IJSRuntime JSRuntime
  5. <Chart Id="pie1" Type="@Chart.ChartType.Pie"
  6. Data="@(new[] { "1", "2" })" BackgroundColor="@(new[] { "blue","green" })"
  7. Labels="@(new[] { "Fail","Ok" })">
  8. </Chart>

Shared/Components文件夹中的My Chart.razor(在调用方法设置时,我在这里得到了错误)

  1. @using System.IO
  2. @inject IJSRuntime JSRuntime
  3. @using Microsoft.JSInterop;
  4. @inject IJSRuntime jsInvoker
  5. <canvas id="@Id"></canvas>
  6. @code {
  7. public enum ChartType
  8. {
  9. Pie,
  10. Bar
  11. }
  12. [Parameter]
  13. public string Id { get; set; }
  14. [Parameter]
  15. public ChartType Type { get; set; }
  16. [Parameter]
  17. public string[] Data { get; set; }
  18. [Parameter]
  19. public string[] BackgroundColor { get; set; }
  20. [Parameter]
  21. public string[] Labels { get; set; }
  22. protected override async Task OnAfterRenderAsync(bool firstRender)
  23. {
  24. // Here we create an anonymous type with all the options
  25. // that need to be sent to Chart.js
  26. try{
  27. var config = new
  28. {
  29. Type = Type.ToString().ToLower(),
  30. Options = new
  31. {
  32. Responsive = true,
  33. Scales = new
  34. {
  35. YAxes = new[]
  36. {
  37. new { Ticks = new {
  38. BeginAtZero=true
  39. } }
  40. }
  41. }
  42. },
  43. Data = new
  44. {
  45. Datasets = new[]
  46. {
  47. new { Data = Data, BackgroundColor = BackgroundColor}
  48. },
  49. Labels = Labels
  50. }
  51. };
  52. await JSRuntime.InvokeVoidAsync("setup", Id, config);
  53. }
  54. catch(Exception e)
  55. {
  56. using (StreamWriter sw = File.AppendText((Pages.CommonClass.error_path)))
  57. {
  58. sw.WriteLine("Chart.JS Error: " + e + Environment.NewLine);
  59. }
  60. }
  61. }
  62. }
iyfjxgzm

iyfjxgzm1#

我已经创建了一个chartiderjs文件,安装程序直接在wwwroot下。然后它就工作了。

相关问题