BlackCat
BlackCat

Reputation: 2044

How to call Server side function in clientside typescript (Serenity)?

I need to call a service(which will return value from an external API call) from a dialog.ts

namespace myNameSpace
{
    [Route("Services/ModuleName/MyObject/[action]")]
    public class MyObjectController : ServiceEndpoint
    {
        [HttpPost]
        public async Task<IActionResult> CreateAsync()
        {
     
            var BaseUrl = "http://localhost:5000/";

            using (var client = new HttpClient())
            {
                MyObject myobject = new MyObject();
                client.BaseAddress = new Uri(BaseUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(username, password);

                HttpResponseMessage Res = await client.GetAsync("api/SomeFunction");
                if (Res.IsSuccessStatusCode)
                {
                    var objResponse = Res.Content.ReadAsStringAsync().Result;
                    myObject = JsonConvert.DeserializeObject<MyObject>(objResponse );
                }
            }
            return Ok(1);
        }

        public class MyObject{
            public string firstProperty { get; set; }
            public string secondProperty { get; set; }
        }

Then, in Dialog.ts, I tried to call the service method in onclick event:

 onClick: () => {

                        Q.serviceCall({
                            url: Q.resolveUrl('~/Services/ModuleName/MyObject/CreateAsync'),
                            request: {
                                
                            },
                            async: false,
                            
                            onSuccess: (response) => {

                                var result = (response as string);

                            },
                            onError: (response) => {
                                //result = "-1";
                            }
                        });

In browser, the button click gives an HTTP 404 error.

Upvotes: 0

Views: 681

Answers (1)

Subarata Talukder
Subarata Talukder

Reputation: 6311

First, Q.serviceCall<>() method by default uses http POST request. So you need to set it up for GET request. I am using jsonplaceholder API for test.

Q.serviceCall<Serenity.RetrieveResponse<any>>({
    service: 'https://jsonplaceholder.typicode.com/posts/22',
    async: false,
    method: "GET",
    onSuccess: (response) => {
        console.log(response);
    },
    onError: (error) => {
        console.log(error.Error);
    }
});

Second, I created and experiment your case in my existing code: I added a new method named GetPost() on PostController class. Then

  • Build >> Build
  • Build >> Transform all T4 templates

Above commands generate a PostService.ts class. Then use this reference on dialog.ts to access your endpoint. On my case:

[RoutePrefix("Services/PostInfo/Post"), Route("{action}")]
[ConnectionKey(typeof(MyRow))]
public class PostController : ServiceEndpoint
{
public ListResponse<MyRow> GetPost()
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Clear();

        Task<HttpResponseMessage> Res = client.GetAsync("https://jsonplaceholder.typicode.com/posts/22");
        if (Res.Result.IsSuccessStatusCode)
        {
            Task<string> reposneData = Res.Result.Content.ReadAsStringAsync();
            reposneData.Wait();

            var myObject = reposneData.Result;
        }
    }

    return null;
}

NOTE: I did not use any Model class that's why I did not return the response back to UI. I debugged this repose on a Watcher.

Post response from API

Write it on dialog.ts class. On my case I wrote this code on my UI.

buttons.push(
    {
        title: Q.text("GetPost"),
        cssClass: 'stampe',
        icon: 'fa-print',
        onClick: () => {
            PostService.GetPost({}, r => {
                console.log(r);
            });
        },
    }
);

Hope you understood, if not please let me comment.

Upvotes: 0

Related Questions