Writing Business Logic to Invoke RESTful Services
To write the business logic to invoke the RESTful API
1. Open the gadgets > HelloWorld > scripts > controller.js in the editor.
2. Decide when the RESTful service should be invoked. To invoke the RESTful service on gadget load, the call should be made through the init block. By default, some RESTful API invocation stubs are auto-generated when a gadget is created. You can enhance the generated stub or create your own.
a. To invoke the RESTful service on gadget load, add the following code in the init section of the gadget's controller.js file.
init : function($scope, restClient,eventBus,log,config) {
try{
.....
this.$scope.restInvocationCORS(config); //ADD THIS BLOCK IN
YOUR INIT
....
}
b. Replace the restInvocationCORS function auto generated under the defineScope block with the following code.
this.$scope.restInvocationCORS = function(gadgetConfig) {
var $scope = this;
var selectedAlias = "MWS1";
$scope.Math=window.Math; // Enable the Javascript Math function
$scope.restClient.url("/rest") //Provide the server alias to connect
to
.serverAlias(selectedAlias)
.remote(true)
.cors(true)
.scope($scope)
.gadgetConfig(gadgetConfig)
.success(function(response, $scope) {
$scope.restData = response; // The RESPONSE will be
captured in a variable called restData
}).error(function(response, $scope, status, headers, config) {
$scope.eventBus.fireEvent(NotificationConstants.ERROR,
"Unable to invoke REST " + gadgetConfig.params.
servers[selectedAlias].host + ":" + gadgetConfig.params.
servers[selectedAlias].port +
"/rest for gadget MWS Remote");
}).invoke();
}
Note:
The server response is captured in a variable called restData. This object is then assigned to the AngularJS $scope object. Assigning it to the $scope object will make the object available for user interface rendering. A sample response for the RESTful API (localhost:8585/rest), is of the following structure:
{
"host": "<HOST>",
"nodeName": "<HOST>-node<NUMBER>",
"httpPort": "8585",
"httpsPort": "0",
"frontEndUrl": "http://<HOST>:<PORT>",
"clusterRoles": "[notification, search, taskengine,
autodeploy]",
"uptime": "17461.0",
"freeMemory": "741135632",
"maxMemory": "954728448"
}