Hello,
I am currently trying to Invoke the api-keys.js file and run KTAccountAPIKeys.init in my Blazor File. My Component looks like this:
@inject IJSRuntime JS
@inject NavigationManager NavManager
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var jsModule = await JS.InvokeAsync<IJSObjectReference>("import", NavManager.ToAbsoluteUri("assets/js/custom/account/api-keys/api-keys.js"));
}
}
}
jsModule.InvokeVoidAsync("KTAccountAPIKeys.init");
@inject IJSRuntime JS
@inject NavigationManager NavManager
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var jsModule = await JS.InvokeAsync<IJSObjectReference>("import", NavManager.ToAbsoluteUri("assets/js/custom/account/api-keys/api-keys.js"));
jsModule.InvokeVoidAsync("KTAccountAPIKeys.init");
}
}
}
Hi,
Sorry for the late reply.
To fix your error you can follow the steps below.
window.KTAccountAPIKeys = KTAccountAPIKeys;
@using Starterkit._keenthemes.libs;
@inject IKTTheme KTTheme;
@inject IJSRuntime JS
@inject NavigationManager NavManager
<script suppress-error="BL9992" src="@KTTheme.GetAssetPath("js/custom/account/api-keys/api-keys.js")"></script>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) {
JS.InvokeVoidAsync("KTAccountAPIKeys.init");
}
}
}
Thank you for the reply, well I understand the concept of setting methods to the global env. But isn't it better to request the file only on the component loaded and not global?
Your Solution will mean that I have to load the file in _LayoutScripts (If I remember the filename, correctly)
Isn't there any other way similar to my attempt above to load the specific JS file only needed for a specific component and then run the methods inside of it?
Also, your solution above works only if the data requests in OnInitializedAsync() isn't taking so long. Because otherwise if Razor is re-rendering stuff since it partially fetched data during OnInitialized --> OnAfterRenderAsync possbily gets called without the needed DOM Element for KTAccountAPIKeys to be present.
Is there any solution you suggest from the side of Metronics beside adding a flag like "IsCompletelyLoaded". Is there any helper function or similar which I can use in my C# to check if element is already present or similar?
Hi,
Yes, you can import and use JavaScript files as a module in your razor components.
export { KTAccountAPIKeys }
@using Starterkit._keenthemes.libs;
@inject IKTTheme KTTheme;
@inject IJSRuntime JS
@inject NavigationManager NavManager
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) {
var module = await JS.InvokeAsync<IJSObjectReference>(
"import", "./assets/js/custom/account/api-keys/api-keys.js");
await module.InvokeVoidAsync("KTAccountAPIKeys.init");
}
}
}