How do I retrieve an async value for a restangular parameter? - javascript

I need to retrieve a value from an async service to add as a parameter to every rest call. The casService.getProxyTicket() is an $http call...
I have the following code :-
myFactories.factory('myFactory', [
'Restangular'
, 'casService'
, function (Restangular
, casService) {
return Restangular.withConfig(function (config) {
config.setBaseUrl('https://host:port/somecontext/rest');
config.addFullRequestInterceptor(function (element
, operation
, route
, url
, headers
, params
, httpConfig) {
... What do I need to do here?
casService.getProxyTicket(url).then(function(st){
console.log('proxyTicket = ' + st.data.ticket);
});
params.ticket = ?????? <= st.data.ticket
...
return {
element: element
, headers: headers
, params: params
, httpConfig: httpConfig
}
});
}).service('myCollection');
}]
);
...thanks in advance!!!!

Ok, my lack of understanding coming from a backend developer's background...
This can/should NOT be done this way! I was trying to make the call to get a proxy ticket synchronous.... DON'T DO IT!
What I did was to rearrange my code thus ...
function readItem(id) {
var endpoint = myFactory.one(id);
return casService.getProxyTicket(endpoint.getRestangularUrl())
.then(function (response) {
return endpoint.get({ticket: response.data.proxyTicket});
}).then(function (response) {
return response.plain();
});
}
...works like a charm!

Related

POST a string value to firebase using angular-1 $http

I using angularjs1 in ionic-1 application and Firebase Database.
And I am trying to post a string to the database using firebase REST API.
I want the data to be in the following format:
Firebase generated Key: "My string"
But what I actually get is :
Can anyone help me to know how to send the data in http post function as a string ?
Here is my code:
.service('postFollowedUser', ['$http', '$q','baseURL', function($http, $q,baseURL){
var deferObject,
myMethods = {
postUser: function(uid,followedUid) {
var myPromise = $http({
method:'POST',
url: baseURL+'users/'+uid+'/followedUsers.json',
data:{followedUid}
}),
deferObject = deferObject || $q.defer();
myPromise.then(
// OnSuccess function
function(answer){
// This code will only run if we have a successful promise.
//alert('answer in servics'+JSON.stringify( answer));
deferObject.resolve(answer);
},
// OnFailure function
function(reason){
// This code will only run if we have a failed promise.
//alert(JSON.stringify( reason));
deferObject.reject(reason);
});
return deferObject.promise;
}
};
return myMethods;
}])
I tried to removing the curly braces but I got the following error:
"Invalid data; couldn't parse JSON object, array, or value."
Not sure if this is supported by firebase, but you are sending payload with object (data:{followedUid} is the same as data:{followedUid: followedUid}).
Try removing the curly braces:
$http({
method:'POST',
url: baseURL+'users/'+uid+'/followedUsers.json',
data: JSON.stringify(followedUid) // payload will be just the value of `followedUid`
})
Btw I am not sure what dark magic are you trying to do with the deferObject :] You can simply return the $http call, its return value is already a promise. You can still call then on it to process the results:
return $http.post(baseURL + 'users/' + uid + '/followedUsers.json', JSON.stringify(followedUid))
.then(function(answer) {
console.log(answer);
// return the answer so you can work with it later (again via `then`)
return answer;
}, function(error) {
console.log(error);
// throw the error so you can catch it later (possibly via `catch`)
throw error;
});

AngularJS - Correctly formatting asynchronous calls

newbie here.
I am trying to understand how I need to structure asynchronous calls within my controller to fit my specific use case:
Consider the following code snippet from an Angular Module in "service.js" within my project:
function getSearchObjects(projectName, title) {
var payload = JSON.stringify({
"title": title
});
var request = $http({
method: 'post',
url: URL + '/search/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
};
function runQuery(projectName, fromDate, toDate, sort, direction, columns) {
var from = Date.parse(fromDate);
var to = Date.parse(toDate);
var payload = JSON.stringify({
"fromDate": from,
"toDate": to,
"sort": sort,
"direction": direction,
"columns": columns
});
console.log(payload);
var request = $http({
method: 'post',
url: URL + '/query/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
return response.data;
};
function handleError(response) {
if (!angular.isObject( response.data ) || !response.data.error) {
return( $q.reject( "An unknown error occurred." ) );
}
return $q.reject( response.data.error );
};
});
Within my controller, I am trying to troubleshoot the following function:
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date, objectProperties.sort, objectProperties.direction, objectProperties.columns)
},
function(error) {
console.log(error);
});
};
getSearchObjects matches a title ($scope.selected.search) selected in my UI and grabs the following more detailed object from an API call:
{ title: 'Duplication Example',
sort: '#_traac-timestamp',
direction: 'desc',
columns: [ '#_traac-remote_ip', 'c-platform-m-distinct-id_s', '_type' ] }
I am trying to grab the properties returned from getSearchObjects and pass them along with a few user selected values from my UI to runQuery, which then returns data from a database to the user, but when I check the values passed to runQuery using the above logic in my controller, I get the following values. All of the objectProperties values I am attempting to pass to runQuery are undefined:
project_name: "Example Project"
start_date: 1499770800000
end_date: 1499943600000
sort: undefined
direction: undefined
columns: undefined
I have been trying to debug this, but I am too new to using Angular and asynchronous calls to really understand what I am doing wrong. My best guess currently is that I am calling runQuery before the values retrieved from getSearchObjects are attached to objectProperties. Either that or I am incorrectly referencing the properties within the objectProperties variable.
Could someone help me troubleshoot this issue, and better understand what I am doing wrong?
Thank you in advance for your help!
When you do this:
var objectProperties = some async function...
You are assigning the promise of the async function to the variable, not the result of it.
The result is coming in the .then, like you declared:
.then(function(result) { ... }
So, instead of objectProperties.sort, objectProperties.direction, objectProperties.columns, try using result.sort, result.direction, result.columns :)
If you are new to Promises, take a look at this simple, but great tutorial.
EDIT
Based on your comment, you are receiving, inside the response.data, the following object:
{"objectMatch": {
"title": "doc-event",
"sort": "#_traac-timestam‌​p",
"direction": "desc‌​",
"columns": [
"m-doc-‌​name_s",
"m-user_s",
"‌​m-full-action-type_s‌​",
"m-event-action-de‌​scriptor_s"
]}
}
So you have: response > data > objectMatch > properties you want.
The response.data you are extracting on your handleSuccess function:
function handleSuccess(response) {
return response.data;
};
So here, your result is response.data, containing the property objectMatch.
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
...
},
...
If all of that is correct, you should be able to access the values you want using result.objectMatch.<sort, direction or columns>, like:
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date,
result.objectMatch.sort, result.objectMatch.direction, result.objectMatch.columns)

Cannot get response content in mithril

I've been trying to make a request to a NodeJS API. For the client, I am using the Mithril framework. I used their first example to make the request and obtain data:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://localhost:3000/store/all"});
}
};
var Component = {
controller: function() {
var stores = Model.getAll();
alert(stores); // The alert box shows exactly this: function (){return arguments.length&&(a=arguments[0]),a}
alert(stores()); // Alert box: undefined
},
view: function(controller) {
...
}
};
After running this I noticed through Chrome Developer Tools that the API is responding correctly with the following:
[{"name":"Mike"},{"name":"Zeza"}]
I can't find a way to obtain this data into the controller. They mentioned that using this method, the var may hold undefined until the request is completed, so I followed the next example by adding:
var stores = m.prop([]);
Before the model and changing the request to:
return m.request({method: "GET", url: "http://localhost:3000/store/all"}).then(stores);
I might be doing something wrong because I get the same result.
The objective is to get the data from the response and send it to the view to iterate.
Explanation:
m.request is a function, m.request.then() too, that is why "store" value is:
"function (){return arguments.length&&(a=arguments[0]),a}"
"stores()" is undefined, because you do an async ajax request, so you cannot get the result immediately, need to wait a bit. If you try to run "stores()" after some delay, your data will be there. That is why you basically need promises("then" feature). Function that is passed as a parameter of "then(param)" is executed when response is ready.
Working sample:
You can start playing with this sample, and implement what you need:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://www.w3schools.com/angular/customers.php"});
}
};
var Component = {
controller: function() {
var records = Model.getAll();
return {
records: records
}
},
view: function(ctrl) {
return m("div", [
ctrl.records().records.map(function(record) {
return m("div", record.Name);
})
]);
}
};
m.mount(document.body, Component);
If you have more questions, feel free to ask here.

jquery is this a valid http request

I have this http request
GET /deals/couchbaseDocument/_search
{
"query" : {
"match" : {
"amenities" : "Maids "
}
}
}
when i put it in curl, it gives me results, i want to build a web app to call that request.
what i did is removing the newlines and put the whole text in .getjson()
as this:
var query = $("#query").val();
query = query.replace(/(\r\n|\n|\r)/gm,"");
$.getJSON(query, function (results) {
alert("success");
alert(results);
})
.success(function () { alert(" second success"); })
.error(function () {
alert("error");
alert(query);
});
i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request
I read this
I found that .getJson could be like this:
$.getJSON('httpURL',
{ parameter1: "parameter value", parameter2: "parameter value" })
i wonder if i should pass my json request as a parameter
in case of the whole picture** i am working on sense elasticsearch plugin
According to the documentation of jQuery's getJson, you can pass a javascript object (jQuery.getJSON() | jQuery API Documentation) so you can do something like this
var queryData = {
"query" : {
"match" : {
"amenities" : "Maids "
}
}
};
$.getJSON('httpURL', queryData)

How to pass an object to AngularJS factory?

I am in edit state i am trying to update riskDto but i am getting an error about some object i dont know what i am doing wrong please help.
Code tried so far...
ctrl.js
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey).then(function (response) {
if ($scope.editMode) {
$scope.hideYesBtn = true;
$scope.hideNoBtn = true;
$scope.showOkBtn = true;
$scope.messageText = 'Updated Risk Within Process successfully';
$scope.confirmationWin.open().center();
$scope.okCallback = $scope.riskAlignToProcessBack;
}
}
});
facotry.js
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}
state.js
.state('createAndAlignRisk', {
url: '/risk/cnaRsk/:processKey',
templateUrl: 'views/risk/createNewRisk.html',
controller: 'RiskCtrl',
data: {
authenticate: true
}
})
consoleError
/riskTocontrol/saveCreateAndAlignNewRiskToProcess/[object%20Object]
If you want to pass both object $scope.riskDTO , $stateParams.processKey to service then the your service method needs to be change along with caller method code
Code
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey)
.then(function (response) {
//..code here
});
Service
saveAllignRiskToProcess: function(processKey, riskDTO) {
var url = 'app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey
return $http.post(url ,JSON.stringify({ 'serverSideParamName': riskDTO}) );
}
From angularjs doc
post(url, data, [config]);
data - Request content
The Data parameter is necessary that you can see from a documentation. You missed it in:
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}

Categories