Ksh*_*ari 2 .net javascript blazor blazor-jsinterop blazor-webassembly
在 blazor 应用程序上工作,它有一个需要从 JS 调用的方法!当我尝试调用没有 static 关键字的方法时,出现此错误 -
The assembly 'AssemblyName' does not contain a public invokable method with [JSInvokableAttribute("INIT_COMPLIANCE")].
Run Code Online (Sandbox Code Playgroud)
一旦我添加静态,它就会识别并加载它。
这是我在 blazor 组件中的代码 -
protected override Task OnInitializedAsync()
{
jsToDotNetBridgeReference = DotNetObjectReference.Create(this);
js.InvokeVoidAsync("SetDotNetReference", jsToDotNetBridgeReference);
return base.OnInitializedAsync();
}
[JSInvokableAttribute("INIT_COMPLIANCE")]
public async void InitComplianceComponent(string token)
{
id_token = token;
Console.WriteLine(token);
await GetData();
}
Run Code Online (Sandbox Code Playgroud)
JS-
self.addNewCompliance = function () {
const url = someurl;
var resource = window.authContext.getResourceForEndpoint(url);
window.authContext.acquireToken(resource, function (error, token) {
// Handle ADAL Error
if (error || !token) {
console.log('ADAL Error Occurred: ' + error);
return;
} else {
Blazor.start().then(() => {
window.InitComplianceComponent(window.DotNet, token);
})
//window.InitComplianceComponent(window.DotNet, token);
}
});
}
Run Code Online (Sandbox Code Playgroud)
BlazorInterop.js
InitComplianceComponent = function (dotnetObj, token) {
dotnetObj.invokeMethod("AssemblyName", "INIT_COMPLIANCE", token);
}
Run Code Online (Sandbox Code Playgroud)
我不想使用 static 关键字作为GetData是非静态方法,并且我无法从静态方法调用它。
我这里哪里错了。
你可以这样做:
protected override async Task OnInitializedAsync()
{
await JSRuntime.InvokeVoidAsync("yourJsFunctionName",
DotNetObjectReference.Create(this), nameof(MethodToInvokeFromJs));
}
[JSInvokable]
public void MethodToInvokeFromJs()
{
//your code
StateHasChanged();
}
Run Code Online (Sandbox Code Playgroud)
你的 js 代码将如下所示:
function yourJsFunctionName(instance, callback) {
instance.invokeMethodAsync(callback);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1662 次 |
| 最近记录: |