This is my first question, excuse my english.
I'm working with angular and I'm using http.post for all (get and post info). And how this is wrong, I'd start to use http.get for request the record from Database.
I'm using this:
$http.get("empresa.php",{params:{id:-1,action:"get"}})
I expect receive something like this:
empresa.php?id=-1&action=get
But not work, because send this:
empresa.php?query=%7B%22id%22:-1,%22action%22:%22get%22%7D
Could you help me?
query is not so I'expect to be.
I'm using Angularjs 1.5.8
EDITION
Te factory is this:
app.factory("Data", ['$http',
function($http, ) { // This service connects to our REST API
var serviceBase = 'service/';
var obj = {};
obj.get = function(q,p) {
console.log(p);
return $http.get(serviceBase + q + ".php",{params:p}).then(function (results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(serviceBase + q + ".php", object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(serviceBase + q + ".php", object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(serviceBase + q + ".php").then(function(results) {
return results.data;
});
};
return obj;
}
]);
for POST work fine, but for GET doesn't work :(
New Edit
Here you can see how is that I have the code, how use and the response
Edit - Finalized
At the end, I resolved using $httpParamSerializer to serialize the json object and put it directly on call to empresa.php
Thanks to all for the help!!!
Use $httpParamSerializer to build the url query for you.
var params = {id:-1,action:"get"};
var query = $httpParamSerializer(params);
$http.get("empresa.php?" + query);
Try not using the $http.get shortcut method.
$http({
url: "empresa.php",
method: "GET",
params: {id:-1, action:"get"}
});
Or else you can create the url yourself.
$http.get('empresa.php?id=' + -1 + '&action=' + 'get');
Related
I'm making http get call from angularJS function. Call works perfectly and get the response back but I need to store response in a variable so I can use it outside of $http. I tried to keep in $scope.data.submissionFileID but alert($scope.data.submissionFileID) says undefined. Also I want me make this call synchronous. I'm new to this, can you please help to modify this below code?
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.data.submissionFileID = response; // response is an integer such as 123
});
alert($scope.data.submissionFileID); // This is undefined, what should I do to fix it?
var content = "<h7><b>" + "Created at </b>" + $scope.data.submissionFileID + "</h7><br><br>";
}
Something to consider is that the alert(...) is being called before the async function has a chance to complete. An option would be to send the response off to another function that sets the $scope variable and does whatever else you might want.
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.doTheThing(response);
});
}
$scope.data = {}
$scope.doTheThing = function(response) {
$scope.data.submissionFileID = response;
}
in the HTML template file...
<div ng-if="!data.submissionFileID">Retrieving Data....</div>
<div ng-if="data.submissionFileID">
<h7><b>Created at </b> {{data.submissionFileID}}</h7>
</div>
I want to change some data before sending it to the server via ng-resource. I use the tranformRequest-Function like this:
update: {
method: 'PUT',
transformRequest: function (data) {
// modify data then
return data;
}
}
I can modify data this way but in the request my data is always serialized. I want keep my data as JSON. Is this possible with transformRequest or have this to be done in controller. I would prefer to do it in the service. Thx for help
Omg i feel like an idiot. You simply have to do
update: {
method: 'PUT',
transformRequest: function (data) {
// modify data then
return angular.toJson(data);
}
}
Here's an example I'm using in my app. Callers of the $resource methods pass in a simple list of parameters as JSON, and the transformRequest bundles the parameters into the format expected by the API I'm using.
var myServices = angular.module('myServices', ['ngResource']);
...
myServices.factory('MyServer', ['$resource', function($resource){
var formatLoginRequest = function(data) {
// input looks like: {username:"imauser", pw:"password"}
// output should be: {request: {cmd:"login", username:"imauser", pw:"password"}}
data.cmd="login";
data = {request: data};
data = angular.toJson(data);
return data;
};
...
return = $resource('https://api.server.com/', {}, {
login: {method:'POST', params:{}, isArray:false, transformRequest:formatLoginRequest },
...other methods defined here...
});
As noted elsewhere, angular.toJson() won't correctly serialize all data types, but it is sufficient for my case with JSON.
In case somebody else comes across this, Angular provides default transformations for objects. The $http service exposes defaults.transformRequest, which checks if the data property is an object and automatically serializes it to JSON.
For this particular case, i would do a simple check if data is an object and if not make it one and override the $http.defaults.transformRequest.
function appendTransform(defaults, transform) {
defaults = angular.isArray(defaults) ? defaults : [defaults];
return defaults.concat(transform);
};
update: {
method: 'PUT',
transformRequest:
appendTransform($http.defaults.transformResponse,function(data) {
data = angular.isObject(data) ? data : {data};
return data;
})
}
Yes it is. A bit troublesome and ulgy but here it is :
// from angular-resource
var toString= function() {
var value = [];
_.forEach(this, function(e) {
value.push('' + e);
});
return '[' + value.join(', ') + ']';
};
var isObject = function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
};
var isFile = function(obj) {
return toString.call(obj) === '[object File]';
}
var isFormData = function(obj) {
return toString.call(obj) === '[object FormData]';
}
var isBlob = function(obj) {
return toString.call(obj) === '[object Blob]';
}
var defaultToJson = function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? angular.toJson(d) : d;
};
this.typeServiceProcessData = function(d){
//[put your code here for to change data this will be called before angular default serialization to the server]
};
this.typeServiceProcessJsData = function(d){
//[for data that come back from the server after getting parse by default angular json parsing]
};
// sample creation of a resource method, be really carefull about the order in transformResponse and transformRequest
'get': {method:'GET', transformResponse:[$http.defaults.transformResponse[0], this.typeServiceProcessData]},
'create': {method:'POST', url:baseResourceUrl, transformRequest:[this.typeServiceProcessJsData, defaultToJson]},
It's a big huge, it's a code i done some time ago and i copy/pasted some function definition from angular-resource because they weren't define in that scope and weren't accessible from outside of angular resource. To see why they're needed check the defaultToJson function i defined which is the angular default.
If someone has a better way to just copy paste that bunch of function i take too :)
My service define like this:
module.factory('portfolio',function(){
var data;
var selectedPort;
return{
getData: function(){
return data;
},
setData:function(portfolios){
data = portfolios;
},
getSelectedPort:function(){
return selectedPort;
},
setSelectedPort:function(portfolioDetail){
selectedPort = portfolioDetail;
}
}
});
And in my controller the code as follows:
module.controller('portfoliosController', function($scope,$http, alertService,stockService, userDataService, portfolio){
var req = {
method: 'get',
url: 'www.facebook.com',
headers: {
'Authorization': userDataService.getToken()
}
};
$http(req).then(function(reponse){
$scope.portfoliosPriceList = reponse['data'];
portfolio.setData($scope.portfoliosPriceList);
console.log(portfolio.getData())//At here,I can get the portfolio's data
}, function(){
alertService.setMessge("System maintenance , please try again later");
alertService.alert();
});
console.log(portfolio.getData())//At here, I cannot get the portfolio's data
});
the error is
Error: undefined is not an object (evaluating 'message.substr')
Anybody can help me to solve this problem?Actually, I really do not understand, why I cannot get the data outside the $http
The request that you do with the $http service is done asynchronously, so the callback that you pass to the .send is not immediately invoked.
The code that follows (the console.log) is executed just after the $http(req) call is made but before the callback is called when the request is responded.
Maybe you will understand better with an simpler example:
function portfoliosController() {
var data = 'Initial Data. ',
content = document.getElementById('content');
// setTimeout would be your $http.send(req)
// calledLater would be your .then(function() { ... })
setTimeout(function calledLater() {
data = 'Data coming from the server takes some time to arrive...';
content.innerHTML = content.innerHTML + data;
}, 1000);
content.innerHTML = content.innerHTML + data;
}
portfoliosController();
<div id="content">
This is because javascript is asynchronous, so the code:
portfolio.getData()
Is maybe executing before the data is returned from the service.
In this case, you should only use the data of the portfolio just after the request is complete (inside the .then() function of $http) or put a promise.
Here is the documentation for angular promises:
https://docs.angularjs.org/api/ng/service/$q
I'm not very good with angular. I want to post to a web service, sending some xml with my search parameters. I don't want to send the parameters in the query string. I've read the official documentation, but I'm still confused. I'm mostly hung up on how to define the $resource to be able to post the way I want.
The error I get is: POST 'https://someWebservice/searchnet'::ERR_INSECURE_RESPONSE
My code is below:
'use strict';
angular.module('app').controller('inventorySearchController', inventorySearchController);
inventorySearchController.$inject = ['$scope','$http', '$resource'];
function inventorySearchController($scope, $http, $resource) {
console.log("controller initialized...");
$scope.callService = function(){
console.log("callService function called...");
var urlSearchService = 'https://someWebservice/search';
var skuVal = $scope.skuField;
var mVenVal = $scope.mVendorField;
//need to somehow specifiy that xml is a #FormParam
var xmlItemSearchRequest = "<ItemSearchRequest>"
+"<skuid>" + skuVal + "</skuid>"
+"<mvendor>" + mVenVal + "</mvendor>"
+"</ItemSearchRequest>";
console.log('calling: ' + urlSearchService + 'sending xml: ' + xmlItemSearchRequest);
var Results = $resource(urlSearchService, {
save: {
method: 'POST',
isArray: true
}
});
var result = Results.save();
console.log('Results: ' + Results);
console.log('result: ' + result);
var successfunction = function(){
$scope.searchResults = data;
console.log('call to ' + urlSearchService + ", was a success.");
};
var errorfunction = function(){
console.error('Calling error', status, data);
};
};
};
The error shown is not about how you posted data. Instead, response was not signed by a valid SSL certificate (or the certificate could not be accepted). That is due to the use of HTTPS protocol. You should consider using HTTP instead.
You can try the approach suggested here to confirm that this is the case.
Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};