2

I’m trying to write a Blazor component that uses google maps via JSInterop. I am trying to call the “DirectionsService” class and “route” method.DirectionsService Route Method

Here is my my local method:

    public async Task<DirectionResponse> Route(DirectionsRequest request)
    {
        var json = await _jsObjectRef.InvokeAsync<string>(
                "google.maps.DirectionsService.route",
                request);

        var directionResponse = JsonConvert.DeserializeObject<DirectionResponse>(json);

        return directionResponse;
    }

This method has two parameters. One is a request object. The second is a callback function. Method Definition

How can I accomplish this using the “InvokeAsync” method?

How do I include the callback function in order to receive the response properly?

1

2 Answers 2

1

You can't include a callback that calls directly into you .NET code.

However, you can pass a callback to another javascript function.

The javascript function is then able to call back to .NET with the standard syntax:

DotNet.invokeMethodAsync('YourApp', 'YourMethodAsync')
1
  • Ok... This is confusing.. So, I will have to create a function in a js file that will be passed in my C# code and that js function will have the reference to the same method that called the js function to begin with? or do I have the js function call another method to post the results? Thanks for the answer.
    – Cyberyaga
    Commented Nov 12, 2019 at 19:27
0

So... This is basically the conclusion I came up with. The code is not final, specially the reject portion but it essentially makes the call to the DirectionsService synchronous using async/await.

Here is the code:

        let promise = new Promise((resolve, reject) => {
            directionsService.route(dirRequest, (result, status) => {
               if (status == 'OK') {
                   resolve(result);
               }
               else
               {
                   reject(status);
               }
            });
        });

        //Wait for promise
        let result = await promise;
        return result;

This essentially allows me respond back to C# function that invoked this javascript function. Now the only thing left is for me to serialize the response back to the C# function, with the bits that I need.

Thanks Postlagerkarte for helping me out.

Not the answer you're looking for? Browse other questions tagged or ask your own question.