Call a Web API
Time to say Hello to an Omnia Fx Web API.
In this part of the tutorial, you will make a client-side component call to a Web API and then display a response message.
Note: The following example will build upon what we have done in Create an extension, so make sure you've been through it.
Step 1. Create a controller
Create a new folder called Controllers
under ..\HelloOmniaFx.Web\
.
Inside the newly created folder, create a new item of typ API Controller Class
with the name TestController
.
Add a GET method in the controller
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace HelloOmniaFx.Web.Controllers
{
[Route("api/test")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
[Authorize]
public string Hello(string name)
{
return $"Hello {name}, nice to meet you. I am Omnia Fx Web API";
}
}
}
Step 2. Call the Web API
Open the file HelloOmniaFxComponent.tsx
.
Inject a HttpClient instance
@Component
export default class HelloOmniaFxComponent extends VueComponentBase implements IWebComponentInstance, IHelloOmniaFxComponent {
//Inject HttpClient
@Inject<HttpClientConstructor>(HttpClient, {
configPromise: HttpClient.createOmniaServiceRequestConfig('[web-service-id]')
}) private httpClient: HttpClient;
...
}
Note: Replace
[web-service-id]
with the guid defined in registerManifest in theomnia.service.ts
file.
Tip: Use the built-in Quick Actions in Visual Studio to automatically import required modules from omnia fx npm. Tip: If Quick Actions can't help you with the needed imports, you can always check the source code of the sample project.
Add new properties and function:
private name = '';
private responseMsg = '';
private waiting = false;
callWebAPI() {
this.waiting = true;
this.httpClient.get<string>('/api/test?name=' + this.name).then((response) => {
this.waiting = false;
this.responseMsg = response.data
})
}
Update the render function:
render(h) {
return (
<div class={this.HelloOmniaFxComponentClasses.container}>
<div class='text-xs-center'>
<div><v-text-field label="Name" v-model={this.name}></v-text-field></div>
<div><v-btn flat loading={this.waiting} onClick={this.callWebAPI}>Send</v-btn></div>
<div><p>{this.responseMsg}</p></div>
</div>
</div>
)
}
Step 3. Test the result
Build and run the project.
Enter your name in the text box, and click the send button.
Wow, your solution has got a backend up and running!