I'm building an app that communicates with an IBM software through REST.
The thing is that I have a POST Method in the NewTicket.controller, but I need to use the user and password on this method to open the ticket.
How can I send the variables (or other thing) that I have on my Login.controller to the NewTicket.controller?
This is my Post Method:
enviar:function() {
var description = this.byId("desc").getValue(); //Recebe o resumo
var long_description = this.byId("long_desc").getValue(); //Recebe a descrição
jQuery.sap.require("sap.m.MessageToast");
sap.m.MessageToast.show(user);
jQuery.sap.require("sap.m.MessageBox");
// open a fully configured message box
sap.m.MessageBox.show("Confirmar a abertura do chamado?",
sap.m.MessageBox.Icon.QUESTION,
"Confirmar",
[sap.m.MessageBox.Action.YES, sap.m.MessageBox.Action.NO],
function(sResult) {
if(sResult == sap.m.MessageBox.Action.YES) //Se clicar em SIM (popup com numero do chamado e tela com lista)
{
var oModel = new sap.ui.model.json.JSONModel();
var url = "http://xxx.xxx.xxx.xx:xxxx/maxrest/rest/mbo/sr/?_lid=" + **user** + "&_lpwd=" + **password** +"&description="+ description +"&description_longdescription=" + long_description + "&_format=json&_compact=true&_verbose=true";
var aData = jQuery.ajax({
type : "POST",
contentType : "application/json",
url : url,
dataType : "json",
async: false,
success : function(data,textStatus, jqXHR) {
oModel.setData({modelData : data});
sap.m.MessageBox.show("ABRIU");
},
error : function(data,textStatus, jqXHR) {
oModel.setData({modelData : data});
sap.m.MessageBox.show(textStatus);
}
})}
else // Se clicar em NÃO
{
}
},
sap.m.MessageBox.Action.YES);
Thank you in advance.
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m"
data-sap-ui-theme="sap_bluecrystal">
</script>
<script>
sap.ui.localResources("app");
var app = new sap.m.App({initialPage:"idinitial1"});
var page = sap.ui.view({id:"loginPage", viewName:"app.login", type:sap.ui.core.mvc.ViewType.XML});
app.addPage(page);
app.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
login.view.xml
<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
controllerName="app.login" xmlns:html="http://www.w3.org/1999/xhtml">
<Page title="Title">
<content>
<Panel headerText = "example" expandable = "true" expanded = "true">
<content>
<Input id="userID" value="User123"/>
<Button text="Login" press="btnClicked"/>
</content>
</Panel>
</content>
</Page>
</core:View>
login.controller.js
sap.ui.controller("app.login", {
btnClicked: function(){
this.userName = this.byId('userID').getValue();
//loading the second view but not placed anywhere, just for showing code usage
sap.ui.view({id:"myTickePage", viewName:"app.ticket", type:sap.ui.core.mvc.ViewType.JS});
}
});
ticket.view.xml can be anything but inside ticket.controller.js:
onInit: function() {
var user = sap.ui.getCore().byId('loginPage').getController().userName;
console.log(user);
},
Output:
Define a variable under the controller scope of Login.controller.
Eg: In Login.controller have a variable this.myValue
In MyTicket.controller:
sap.ui.getCore().byId('loginViewID').getController().myValue
This will work as long as your login view/controller are not destroyed.
Suppose two views:
login view corresponding to Login.controller (viewid_login)
ticket view corresponding to NewTicket.controller (viewid_ticket)
In Login.controller:
onInit: function() {
this.userName= "User123";
},
In NewTicket.controller:
onInit: function() {
var user = sap.ui.getCore().byId('viewid_login').getController().userName;
//this will return "User123"
},
Hope this makes it clear.
Note that your login view should not be destroyed.
Depends where you are storing the user and password. The correct way would be to actually store them in the model. Initialize the model on the onInit and then get them when you need them.
onInit: function() {
..
var data = {user: 'bla', password: 'ble'};
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
sap.ui.getCore().setModel(oModel);
..
}
then on the view you can get the values with:
var oModel = sap.ui.getCore().getModel();
var data = oModel.getData();
//data.password
//data.user
Related
I just followed the startup tutorial to load up a model.
Firstly I have a exsiting client_id and client_secret from autodesk developer, and then built up a express based application with client_id and client_secret in order retrieve the access token such as
var config ={
credentials: {
client_id: 'xxxxxxxx',
client_secret: 'xxxxxxx',
grant_type: 'client_credentials',
scope:'data:read data:write data:create bucket:create bucket:read'
},
BaseEndPoint: 'https://developer.api.autodesk.com',
Version: 'v1'
} ;
config.AuthenticateEndPoint =config.BaseEndPoint + '/authentication/' + config.Version + '/authenticate' ;
unirest.post (config.AuthenticateEndPoint)
.header ('Accept', 'application/json')
.send (config.credentials)
.end (function (response) {
}
{"access_token":"ruTBP6POxlpcy8HK2KlWzoFu61oE","token_type":"Bearer","expires_in":86399}
This access token is then sent back to a simple html client.
<!DOCTYPE html>
<html>
<head>
<title>Very Basic 3D Viewer</title>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<script src="js/jquery-3.1.1.min.js" ></script>
<!-- The Viewer CSS -->
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/style.min.css" type="text/css">
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/A360.css" type="text/css">
</head>
<body>
<div id="viewer"></div>
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/three.min.js?v=v1.2.22"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js?v=v1.2.22"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/Autodesk360App.js"></script>
<!-- Developer JS -->
<script>
$(document).ready(function () {
var viewerApp;
var options = {
env: 'AutodeskProduction',
accessToken: 'YOUR ACCESS TOKEN'
};
var documentId = 'YOUR BASE 64 ENCODED URN';
$.getJSON( 'http://'+window.location.host+ "/gettoken", function( data ) {
console.log(data);
options.accessToken = data.accessToken;
documentId = data.urn;
options.document = data.urn;
});
console.log(options.accessToken, documentId);
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
});
</script>
</body>
</html>
The problem occurred on the client-side, which can successfully get the access token. However this gave me a error
'POST https://developer.api.autodesk.com/utility/v1/settoken 401 (Unauthorized)'
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
i can't figure out what is the problem, something wrong with api or client side or server side?
Note: on registering the developer api, i simply named callback as http://localhost:3000 because currently i am testing it on the local environment, is that the problem ?
The code here
var config ={
credentials: {
client_id: 'xxxxxxxx',
client_secret: 'xxxxxxx',
grant_type: 'client_credentials',
scope:'data:read data:write data:create bucket:create bucket:read'
},
BaseEndPoint: 'https://developer.api.autodesk.com',
Version: 'v1'
} ;
config.AuthenticateEndPoint =config.BaseEndPoint + '/authentication/' + config.Version + '/authenticate' ;
unirest.post (config.AuthenticateEndPoint)
.header ('Accept', 'application/json')
.send (config.credentials)
.end (function (response) {
}
is correct. You get a valid access token, and I assume you run this code from your node.js server. On your server you implement an endpoint, i.e /gettoken, which your client app will call to get the access token returned to your page which initialize the viewer. So far so good.
However, when you consider the calling sequence on your client, there is an issue.
$(document).ready(function () {
means that your code will execute when the DOM is ready - this is fine.
Here, you initialize your variables:
var options = {
env: 'AutodeskProduction',
accessToken: 'YOUR ACCESS TOKEN'
};
var documentId = 'YOUR BASE 64 ENCODED URN';
until here it is still ok, but note that both the accessToken and documentId have invalid valid.
Next, you query the access token using $.getJSON() which is an asynchronous way of calling an endpoint. That means this function returns immediatelly before you read the reply.
So the next code executed is not the one in the callback function, but this one:
console.log(options.accessToken, documentId);
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
at this time, the accessToken and documentId still got invalid values, which will cause your code to fail. In short you need to initialize the Viewer from the callback to wait for the /gettoken response to come back.
$.getJSON( 'http://'+window.location.host+ "/gettoken", function( data ) {
console.log(data);
options.accessToken = data.accessToken;
documentId = data.urn;
options.document = data.urn;
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
});
Code is as follows
var myApp = angular.module("gameModule", []);
myApp.controller("gamecontroller", function ($scope) {
$scope.message = "test";
// websocket connection.
var gameHub = $.connection.socketHub;
$.connection.hub.start().done(function () {
var clientid = $.connection.hub.id;
$(function () {
var user = { signalrsessionid: clientid };
$.ajax({
type: "POST",
data: JSON.stringify(user),
url: "http://localhost:53629/api/game/signalr",
contentType: "application/json"
}).done(function (response) {
alert(response);
$scope.responsemessage = response;
});
});
});
});
and front end code
<!DOCTYPE html>
<html ng-app="gameModule">
<head>
<title>game registration</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.js"></script>
<script src="Scripts/angular.js"></script>
<!--Automatisch gegenereerde signalR hub script -->
<script src="signalr/hubs"></script>
<script src="Scripts/rouletteAngular.js"></script>
</head>
<body>
<div ng-controller="gamecontroller">
{{ message }}
{{ responsemessage }}
</div>
So the 'message' is being displayed, the alert box with the response is showing the correct response, but the responsemessage doesnt show any value.
Can anyone tell me what i'm doing wrong.
you must call $scope.$apply(); or $scope.$digest(); after setting $scope.responsemessage = response; because you are using jQuery ajax call, which is outside Angulars context.
EDIT:
here you have nice way to use SignalR in AngularJS:
http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html
I would really appreciate guidance.
My script will make a call to my server, grab some data and bring it back as JSON. Then I call ServiceSucceeded(msg); I pass in the JSON results in msg. Now in ServiceSucceeded I want to display my results on kendoui grid. That is the part that I can't get to work. It gives no browser errors.
This code might be awful, so please school me on this , thanks!
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.common.min.css" />
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.default.min.css" />
<script src="../../assets/telerik/js/jquery.min.js"></script>
<script src="../../assets/telerik/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid">
</div>
<div>
<script>
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var Username;
var Password;
var qryVar;
var locationName;
function GetAllReportDB() {
var dataId = "1";
Type = "GET";
qryVar = "userName=Simon"
Url = "http://localhost/UserReportMap.svc/GetAllReportDB?" + qryVar;
Data = '{"Contains": "Kir","DBName":"Bony","Operator":"BON0D"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; ProcessData = true;
Username = "test";
Password = "test";
CallService();
}
function CallService() {
$.support.cors = true;
$.ajax({
cache: false,
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
beforeSend: function (xhr2) {
xhr2.setRequestHeader("Authorization", "Basic " + window.btoa(Username + ':' + Password));
},
success: function (msg) {
ServiceSucceeded(msg);
alert("Succeeded");
},
error: function (errMsg) {
alert("Fail!");
}
});
}
function ServiceSucceeded(msg) {
var myResults = { "d": [{msg}] };
alert(JSON.stringify(msg));
$(function () {
$("#grid").kendoGrid({
dataType: "json",
schem: {
data: "d"
}
//columns: [{ title: "First Name" },
// { title: "Last Name" }]
});
});
}
$(document).ready(
function () {
GetAllReportDB();
}
);
</script>
</div>
</body>
</html>
Well, you have one typo at schem. It should be schema and not schem.
Anyway, I recommend check API docs, there is written what you need.
And to your question:
You are missing dataSource in your grid so it doesn't know from what data grid should be rendered.
$("#grid").kendoGrid({
dataSource: {
type: "json",
data: jsonData,
pageSize: 20
},
...
});
So line var myResults = { "d": [{msg}] }; can be removed and msg data can be assigned into dataSource. Then you will be able to set columns - here demo
And also consider, if you need load your json data in function and result assign into variable. Grid is able to load data from server without that - server just has to return json data, like in this example
I make a web services which returns me a JSON formatted data when I use this url(http://localhost:8080/jerseyweb/crunchify/ftocservice). Now I want to get those data through Angular js but I can not get it. The code with which I try that is as follow:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.id + ', ' + x.name }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
alert("hi");
$http.get("http://localhost:8080/jerseyweb/crunchify/ftocservice")
.success(function (data, status, headers, config) {
alert("hiee"); // i can not reach at this alert
$scope.names = data;
});
});
</script>
</body>
</html>
The JSON data in http://localhost:8080/jerseyweb/crunchify/ftocservice is as following
[{"id":98.24,"name":36.8}]
There is an error in Web Services Response.....
#OPTIONS
#Path("/getsample")
public Response getOptions() {
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.build();
}
Please try this code might be it's use full :
var response = $http({
method: "GET",
url: "http://localhost:8080/jerseyweb/crunchify/ftocservice",
dataType: "json"
});
response.then(function (obj) {
$scope.names = obj.data.name;
}, function () {
alert('Error.');
});
If data comes from the API in string format then use
var objdata = JSON.parse(obj.data);
$scope.names = objdata.name;
Im very new to Backbone.js and have been following a couple tutorials to come up with the script below. What I am trying to achieve is retrieving JSON data from a rest api when my routes are used. If you look at the people function for the friends route you can see where im going with this. Where am i going wrong?
<!DOCTYPE html>
<html>
<head>
<title>I have a back bone</title>
</head>
<body>
<button id="add-friend">Add Friend</button>
<ul id="friends-list">
</ul>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script>
Friend = Backbone.Model.extend({
name: null,
age: null,
});
FriendDetailModel = Backbone.Model.extend();
FriendDetailCollection = Backbone.Collection.extend({
url: 'slim/index.php/friends/',
model: FriendDetailModel
});
Friends = Backbone.Collection.extend({
initialize: function(models, options) {
this.bind("add",options.view.addFriendLi);
}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function() {
this.friends= new Friends(null, {view:this});
},
events: {
"click #add-friend": "showPrompt",
},
showPrompt: function () {
var friend_name = prompt("Who is your friend?");
var friend_age = prompt("What is your friends age?");
var friend_model = new Friend({name: friend_name, age: friend_age});
this.friends.add(friend_model);
},
addFriendLi: function(model) {
$("#friends-list").append("<li>" + model.get('name') + " " + model.get('age') + "</li>");
}
});
var appview = new AppView;
AppRouter = Backbone.Router.extend({
routes: {
"friends":"people",
"person/:name":"personDetail"
},
people: function() {
console.log('all the people');
var people = new FriendDetailCollection;
people.fetch({
success: function(data) {
console.log(data);
}
},
personDetail: function(name) {
console.log('one person named ' + name);
}
});
var approuter = new AppRouter;
Backbone.history.start();
</script>
</body>
</html>
after running people.fetch Console.log shows
d
_byCid: Object
_byId: Object
length: 4
models: Array[4]
__proto__: x
If i do console.log(data.toJSON()); it returns
[]
I ended up resolving the problem by doing the following:
I created a new collection outside of the router:
var people = new FriendDetailCollection;
When I created the view I specified the collection I previously created.
friendview = new FriendView({collection: people});
I had a typo in my FriendView. Previously I had _.bind(this, 'render'). It need to be
_.bindAll(this,'render');
Also, i put my console.log in the render() function within my FriendView.
FriendView = Backbone.View.extend({
el: $("body"),
initialize: function() {
_.bindAll(this,'render');
this.collection.bind('reset', this.render);
},
render: function() {
console.log(this.collection.toJSON());
}
});