Reputation: 2044
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
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
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.
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