【问题标题】:Issues with using js interop for blazor hybrid app将 js 互操作用于 blazor 混合应用程序的问题
【发布时间】:2021-07-09 13:21:53
【问题描述】:

当我尝试在混合 blazor 应用程序中通过互操作调用名为 initMap 的 js 函数时,我不断收到以下错误:

在“窗口”中找不到“initMap”

我有以下代码:

TestApp.Windows\wwwroot\index.html

...
<head>
<script src="../js/initGoogleMap.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script>
</head>
...

TestApp.Windows\wwwroot\js\initGoogleMap.js

window.initGoogleMap = {
    initMap: function () {
        const latLng = new google.maps.LatLng(40.716948, -74.003563);
        const options = {
            zoom: 14,
            center: latLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        const map = new google.maps.Map(document.getElementById("map"), options)
    }
};

TestApp\WebUI\Pages\Index.razor

@page "/"
@inject IJSRuntime JSRuntime

<h1>Hello, world!</h1>

Welcome to your new app.

<div id="map" style="height:500px; width:100%;"></div>

@code{
    protected override async Task OnAfterRenderAsync(bool firstRender) {
        if (firstRender)
        {
            Console.WriteLine("first render");
            await JSRuntime.InvokeVoidAsync("initMap");
        }
    }
}

任何想法为什么会发生此错误?我尝试了几个小调整,但无济于事。任何帮助将不胜感激!

【问题讨论】:

  • 你的 js 路径有两个点和一个斜线。那是一个目录。与索引所在的位置相比,它实际上位于子目录中。

标签: javascript blazor


【解决方案1】:

【讨论】:

  • 还请说明您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
【解决方案2】:

很可能静态文件没有复制到工作目录中。以下是处理该问题的一些步骤:

  1. 在公共项目中确保所有静态资源都设置为 “如果较新则复制”(在文件的属性中)

  2. 在 index.html 文件中,请设置文件路径以匹配以下模式:

    "_content/<PROJECT_NAME>/path/to/the/file.js"
    

你的情况是:

"_content/TestApp/js/initGoogleMap.js"
  1. 删除每个项目中的所有 bin 和 obj 文件夹并重建整个解决方案。
  2. 如果 Android 问题仍然存在,请从 android 模拟器中卸载该应用并重复第 3 步。

附:这是 Blazor Binding 存储库中问题的链接:https://github.com/dotnet/MobileBlazorBindings/issues/211

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 2019-12-24
    • 2020-02-28
    • 2020-10-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多