csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', function ($scope, $http, $document, $resource) {
$scope.clientResult = {};
$scope.data = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '5555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
'url': $scope.clientResult.resource_server_base_uri + 'services/v6.0/agent-sessions',
'method': 'POST',
'headers':{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
'data': JSON.stringify($scope.startSessionPayload)
}).success(function(data, status, headers, config) {
$scope.data = data;
console.log('data', $scope.data)
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}]);
The code above gives me a 404 when I try te $http "POST".
When I console.log($scope.clientResult.resource_server_base_uri), I get: "https%3a%2f%2fapi-c7.incontact.com%2finContactAPI%2f".
But, I get a 404, and when I look in developer tools, I see it's trying to post to : "http://localhost:63342/Call_cntr/client/https%3a%2f%2fapi-c7.incontact.com%2finContactAPI%2fservices/v6.0/agent-sessions"
I'm starting to think it's failing because the "://localhost..." is being "prepended" to the base_uri... Not sure why this is happening. I feel I'm providing everything mentioned in the inContact API docs. Maybe it's with my angular conversion from AJAX to $http ??
Any help, much appreciated, I'm stuck..
Once you have an API Authentication Token, you use this token to create an agent session for the agent whose credentials you used to get the token. This is done by requesting the https://api-{cluster}.incontact.com/inContactAPI/services/v6.0/agent-sessions method, and supplying either a "station ID" or a phone number which will be delivered to the agent.
per the docs : https://developer.incontact.com/API/AgentAPI#!/Sessions/startSession
Try
result.resource_server_base_uri = unescape(query_string.resource_server_base_uri);
I believe that / is actually a seperator, but %2f becomes an ordinary character that simply represents / character in your url.
unescape() is deprecated; try decodeURIComponent()
Related
I have a strange situation as follows:
The Web-Client application I'm working is based on JQuery and AngularJS,
I have deployed a TOMCAT server (8.5) and a servlet (JAVA-based developed on Eclipse).
The code sending the requests from follows:
var MyApp = angular.module('MyApp');
MyApp.factory('DB_Services', ['$http' , '$q' , function($http , $q) {
var l_Result ;
var DB_Services = function(p_URL_Root , p_Query) {
var l_deferred = $q.defer();
var l_params = JSON.stringify(p_Query) ;
var l_url = "http://localhost:8080/MEKUWQDispatcher/DispatcherClass";
var l_params = 'request=' + encodeURIComponent(JSON.stringify(p_Query)) ;
var req = { url : l_url,
method :"GET",
timeout:10000 ,
headers: {
'Content-Type': 'application/json ; charset=UTF-8'
},
data:l_params
} ;
$http(req ).
success(function(data, status, headers, config) {
l_deferred.resolve(data);
}).
error(function(data, status, headers, config) {
l_deferred.resolve(status);
});
return l_deferred.promise;
return l_deferred.promise;
} ;
return DB_Services;
}]);
Now, the Servlet includes both GET and POST methods. The GET method works in two ways: If the request contains data, it uses the received data to invoke a DB stored procedure. If no data in the request, it invokes a hardcoded select statement (this second behavior is the simple way I found to verify proper connection to the DB, and it would never be activated in real life; moreover, I may eventually delete that part from the servlet's code).
When using a browser (IE, CHROME, all the same result) and enter the address:
http://localhost:8080/MEKUWQDispatcher/DispatcherClass
I get the result of the hardcoded select statement as expected. If, on the other hand, I enter some data to the request, something like:
http://localhost:8080/MEKUWQDispatcher/DispatcherClass?data="request={blabla}"
I get error 400 (bad request).
Now, switching to the javascript, no patter what I do (with or without data) I always get the result of the hardcoded select statement.
I also added the declaration of the servlet within the web.xml file as follows:
<servlet>
<servlet-name>MEKUWQDispatcher</servlet-name>
<servlet-class>MEKUWQDispatcher.DispatcherClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MEKUWQDispatcher</servlet-name>
<url-pattern>/MEKUWQDispatcher</url-pattern>
</servlet-mapping>
Since the original post I made several changes to the service code, being the following a copy of the new code that works like a charm (note also that I switched from GET to POST method):
var MyApp = angular.module('MyApp');
MyApp.factory('DB_Services', ['$http' , '$q' , function($http , $q) {
var DB_Services = function(p_URL_Root , p_Query) {
var l_deferred = $q.defer();
var l_params = JSON.stringify(p_Query) ;
var l_url = "http://localhost:8080/MEKUWQDispatcher/DispatcherClass";
var req = { url : l_url,
method :"POST",
timeout:600000 ,
headers: {
'Content-Type': 'application/json ; charset=UTF-8'
},
params:{request:p_Query}
} ;
$http(req ).
success(function(data, status, headers, config) {
l_deferred.resolve({Server_Response:data , Server_Status: status});
}).
error(function(data, status, headers, config) {
l_deferred.resolve(status);
});
return l_deferred.promise;
return l_deferred.promise;
} ;
return DB_Services;
}]);
In my console the error is coming "getIdData is not defined" what is wrong with my code. Here deal is my service and getIdData is my function in service.
$scope.editUserDetail = function editUserDetail(){
$scope.showEditView = !$scope.showEditView;
$scope.showSubmitView = !$scope.showSubmitView;
console.log(deal);
deal.getIdData().then(function successCb(data){
$scope.editIdOptionsData=data;
});
};
Please check working example here: Demo
You are forget to return service object from service.
i.e
Write following code in your service,
return service;
i.e
angular.module('account').service('deal', function deal($http, accountConfiguration, $q, $log, httpHelper) {
var service = {};
var baseUrl = account.app.url;
service.getIdData = function(data, accountId, decisionMakerDetail) {
var def = $q.defer();
var url = baseUrl + '/api/accountsusers/' + accountId + '?role=' + decisionMakerDetail;
httpHelper._$http({
method: 'post',
url: url,
data: data,
def: def
}, function(resp) {
def.resolve(resp.msg);
});
return def.promise;
};
return service;
});
Or as you are using service you can write it using this
angular.module('account').service('deal', function deal($http, accountConfiguration, $q, $log, httpHelper) {
var baseUrl = account.app.url;
this.getIdData = function(data, accountId, decisionMakerDetail) {
var def = $q.defer();
var url = baseUrl + '/api/accountsusers/' + accountId + '?role=' + decisionMakerDetail;
httpHelper._$http({
method: 'post',
url: url,
data: data,
def: def
}, function(resp) {
def.resolve(resp.msg);
});
return def.promise;
};
});
For more information please check - Services
Please clean your browser and inspect source.Look deal.getIdData() is loaded or not.May be it is not loaded.Please load properly.
The object you are sending as a parameter doesn't have the getIdData() function defined.
Change your log to:
console.log(deal.getIdData);
and then check whether it returns the function code/definition.
Here is a link with an example of how implement a factory and service.
Angular factory and service
You are not returning the object holding the service reference from you your service registration function. Change your code as below for it to work.
angular.module('account')
.service('deal', function deal($http, accountConfiguration, $q, $log, httpHelper) {
var service = {};
var baseUrl = account.app.url;
service.getIdData = function(data,accountId,decisionMakerDetail){
var def = $q.defer();
var url = baseUrl + '/api/accountsusers/' + accountId + '?role=' + decisionMakerDetail;
httpHelper._$http({
method: 'post', url: url, data: data, def: def
}, function (resp) {
def.resolve(resp.msg);
});
return def.promise;
};
return service;
});
S8nce you were not returning anything from the service, even though deal service gets registered, its value is undefined and when you try to access deal.getIddata() you get the aforementioned error
how to access the response inside controller from a nested $http which is inside a factory. here we are having two service calls.one inside another.I need the response of the second service call in my controller. I am able to access the factory from controller and also the response inside the factory but when comes to controller success function, it's showing success function is not defined.
factory code : here i am calling nested $http service calls
bosAppModule.factory("ServiceCalls",function($http){
var ServiceCalls={};
var createFilterString = function(crudObject, callback) {
var filterString = "";
var keyValuePairs = [];
// iterate over the property
for(var property in crudObject) {
if(!(crudObject[property] instanceof Object)) {// if it is primitive type
// check the value is not null or undefined
if(crudObject[property] && crudObject[property] != "")
// added the key value string
keyValuePairs.push(property + "~;~" + crudObject[property]);
}
}
// add first key value pair
if(keyValuePairs[0])
filterString += keyValuePairs[0];
// iterate over the key value strings
for(var i = 1; i < keyValuePairs.length; i++) {
filterString += "~$~" + keyValuePairs[i];
}
try {
if(callback) callback(filterString);
} catch(e) {
console.log("Exception inside $dataTransactor->createFilterString" + e.message);
}
};
// var headers = {Authorization: COOKIES.readCookie("Authorization"),requestmode:"ACK_URL"};
// headers.isRender = file.isRender;
// if(file.inputDataHeaders)
// headers.inputData = file.inputDataHeaders;
ServiceCalls.getData = function(filterObject, file){
createFilterString(filterObject, function(filterString){
var headers = {Authorization: COOKIES.readCookie("Authorization"),requestmode:"ACK_URL"};
headers.isRender = file.isRender;
if(file.inputDataHeaders)
headers.inputData = file.inputDataHeaders;
$http({
method: 'GET',
url: file.fileUrl + "/" + $securityComponent.cryptograghicFunctions.encryptor(filterString),
headers: headers
})
.then(function(requestHandlerResponce) {
console.log(requestHandlerResponce);
$http({
method: 'GET',
url: requestHandlerResponce.data.links[1].href,
headers: headers
}).then(function(responceHandlerResponce) {
console.log("##### : "+JSON.stringify(responceHandlerResponce.data));
return responceHandlerResponce;
});
})
});
};
return ServiceCalls
});
controller code : here I need the response
bosAppModule
.controller(
"custom-entity-design-ctrl",
function($scope, $document, $http, $localStorage, navigateEntityUrl, entityFormation,layoutDesignFactory, ServiceCalls) {
var layoutDesignFac=new layoutDesignFactory();
var entityJson='{"entityInfo":{"entity":"","tenantId":"2b69af63-e2dc-43e5-9f0e-9fde52032d4c","timeStamp":"Tue Jun 16 2015 19:05:09 GMT+0530 (India Standard Time)"},"collections":{"Entity":{"meta":{"parentReference":"***","pkName":"***","fkName":"***"},"rowSet":[],"rowFilter":[]}}}';
var crudObject = {};
var file = {
fileUrl: $config.UIMetaData,
inputDataHeaders: entityJson
};
ServiceCalls.getData(crudObject,file).success(function(response){console.log(response)});
});
Your services should be returning the promises (the $http call in your case) to the controller:
return $http({ // return this promise
method: 'GET',
url: file.fileUrl + "/" + $securityComponent.cryptograghicFunctions.encryptor(filterString),
headers: headers
}).then(function(requestHandlerResponce) {
console.log(requestHandlerResponce);
return $http({ // return this promise as well
method: 'GET',
url: requestHandlerResponce.data.links[1].href,
headers: headers
}).then(function(responceHandlerResponce) {
console.log("##### : "+JSON.stringify(responceHandlerResponce.data));
return responceHandlerResponce;
});
And just to be consistent try to use the standard .then method rather than .success or .error in your controller:
ServiceCalls.getData(crudObject,file).then(function(response) {
console.log(response)
});
Last somewhat irrelevant note, I think 'response' is misspelled in your service ;)
I'm trying to create a simple movie app in Angular. I can do a JSON request to the tmdb (the movie database) api and show the raw result on my homepage. But my problem is that I can't seem to only show the title of the movies from the JSON request.
examplecontroller.js.coffee
angular.module('app.exampleApp').controller('exampleCtrl', [
'$scope', '$http', function($scope, $http) {
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular';
var apiKey = 'a8f703963***065942cd8a28d7cadad4';
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
$scope.movieList = 'requesting...';
$http.jsonp(url).then(function(data, status) {
$scope.movieList = JSON.stringify(data);
console.log($scope.movieList)
},function(data, status) {
$scope.movieList = JSON.stringify(data);
});
}
]);
show.html.haml
#search{"ng-app" => "app.exampleApp"}
%div{"ng-controller" => "exampleCtrl"}
%div{"ng-repeat" => "movie in movieList track by $index"}
{{movie.title}}
When I check the elements in Chrome I see that I have about 25.000 ng-repeat divs. But all without content.
I've been following this tutorial for a bit (and some other sources) and something I don't understand is the movie in Movielist. I know that movielist is the whole json request but what is movie?
Solved
controller
angular.module('app.exampleApp').controller('exampleCtrl', [
'$scope', '$http', function($scope, $http) {
var base = 'http://api.themoviedb.org/3';
var service = '/movie/popular';
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4';
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
$scope.movieList = [];
$http.jsonp(url).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.movieList = data.results;
console.log($scope.movieList)
} else {
console.error('Error happened while getting the movie list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
}
]);
show
%h1
Logo
%li
= link_to('Logout', destroy_user_session_path, :method => :delete)
#search{"ng-app" => "app.exampleApp"}
%div{"ng-controller" => "exampleCtrl"}
%div{"ng-repeat" => "movie in movieList"}
{{ movie.original_title }}
Your problem is you are taking the javascript array returned to the request callback as data and converting it into a string using JSON.stringify().
Then when you pass this string to ng-repeat it is looping over every character in that string. Thus you have a huge number of repeated <div> but since each is a string containing one character there is no title property of that string to print
Pass the array directly to your scope variable in the request callback.
Change:
$scope.movieList = JSON.stringify(data);
To:
$scope.movieList = data;
JSON is a string data format. When $http receives that string response it will internally parse it to a javascript object/array. You should not need to transform it yourself
I have no idea what i'm doing wrong, all of my other services work no problem. What i'm attempting to do is upload a photo. Originally the service part of the code was inside the controller, and i refactored it to be a service because I didnt want to write another whole set of code to upload again after editing a photo(This is what service is for right?)
controller:
app.controller('UploadCtrl', ['$scope', '$upload','UploadService',
function($scope, $upload,UploadService) {
$scope.uploads = [];
var photos = $scope.$parent.photos;
for (i = 0; i < 3; i++) {
$scope.uploads[i] = {
id: i+1,
showLink: photos[i].showLink,
showProg: false,
progress: 0,
photoUrl: photos[i].dataUrl
}
}
}
]);
factory:
app.factory('UploadService',['$upload', '$scope', function($upload,$scope){
$scope.onFileSelect = function($files, $_upload) {
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
//set thumbnail
$scope.dataUrl = null;
if ($file.type.indexOf('image') > -1) {
var fileReader = new FileReader();
fileReader.readAsDataURL($file)
var loadFile = function(fileReader) {
fileReader.onload = function(e) {
// console.log(e.target.result);
$_upload.dataUrl = e.target.result;
$_upload.showLink = false;
$_upload.showProg = true;
}
}(fileReader);
}
$scope.upload = $upload.upload({
url: 'upload_picture',
method: 'POST',
file: $file,
fileFormDataName: 'provider[photo_' + $_upload.id + ']'
}).progress(function(event) {
$_upload.progress = parseInt(100.0 * event.loaded / event.total);
// console.log('percent: ' + $_upload.progress);
}).success(function(data, status, headers, config) {
// file is uploaded successfully
// console.log("success")
// console.log(data);
$_upload.showProg = false;
}).error(function(data, status, headers, config) {
console.log("error");
});
}
};
var UploadService = $scope.onFileSelect($files,$upload);
return UploadService;
}]);
based off this:
https://github.com/danialfarid/angular-file-upload
First and foremost, a service cannot take dependency on scope, so you cannot inject $scope (can inject $rootScope). You cannot copy and paste code from your controller implementation and paste into service.
The factory service needs to create service object and then attach functions and return at last
app.factory('UploadService',['$upload', function($upload){
var service = {};
service.upload = $upload.upload({
...
});
return service;
}]);
You can't inject $scope into a factory / service. You can use $rootScope, but you should probably be returning a promise from your factory.
Here is another similar question. Angularjs factory: errors on passing $scope,$route,$http?
app.factory('UploadService',['$upload', '$q', function($upload, $q){
var deferred = $q.defer();
return{
upload: function(uploadConfig){
$upload.upload(uploadConfig)
.success(function(data){
deferred.resolve(data);
}).error(function(error){
deferred.reject(error);
});
return deferred.promise;
}
}
}]);