I try to get response data from angular service created by factory and $resource. I want to send POST request to server to create object in db and received created ID.
So I create service like this:
angular.module('sample')
.factory('Client', function ($resource) {
return $resource('api/clients/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
I use Client service in controller:
$scope.create = function () {
Client.save($scope.client,
function (response) {
$state.go("clientDetail", {'id' : whereIsMyId.id? })
});
};
Unfortunately, I do not know how to read data in response.
As response I just get number like "6" but this could be any JSON.
Thank you.
Related
I need to create service in AngularJS to return the response of HTTP requests. My problem is the asynchronous request, because after I've submitted the request, my function returns undefined instantly and does not return the response from the server.
app.service('TesteService', function($http) {
this.teste = function(data) {
var data = "*";
$http({
method: 'GET',
url: 'teste-s.php',
params: {data: "bem recebido"}
}).then(function successCallback(response) {
data = response.data;
alert(data);
return data;
}, function errorCallback(response) {
data = "500";
});
}
});
How do I fix this?
I have a service in separate JS file, this service is like OOP class that holds 'methods' to load necessary data from the web.
I want call those 'methods' and get the data in my main JS file, actually I want to load data of three types and force JS flow to wait untill that data is retrieved, here's my code:
services.js
// My 'Class' to load data from the web server
myApp.factory("LoadData", ["_gl", function (_gl) {
return {
GetUsers: function ($http) {
$http({
method: 'POST',
url: 'http://localhost/dgis/ps/select.php',
data: { "action": "GetUsers" }
}).then(function successCallback(response) {
// Save the response JSON object to my global objects
_gl.myUsers = response.data;
}, function errorCallback(response) {
console.log("GetUsersError:" + response);
});
},
GetObGroups: function ($http) {
$http({
method: 'POST',
url: 'http://localhost/dgis/ps/select.php',
data: { "action": "GetObGroups" }
}).then(function successCallback(response) {
// Save the response JSON object to my global objects
// This code fills array because it iterates through it
angular.forEach(response.data, function (value, key) {
_gl.myObGroups.push(value)
});
}, function errorCallback(response) {
console.log("GetObGroups:" + response);
});
},
GetObjects: function ($http) {
$http({
method: 'POST',
url: 'http://localhost/dgis/ps/select.php',
data: { "action": "GetObjects" }
}).then(function successCallback(response) {
_gl.myObjects = response.data;
}, function errorCallback(response) {
console.log("GetObjectsError:" + response);
});
}
}
}]);
// My global variables
myApp.factory('_gl', function () {
return {
myUsers: [],
myOrganisations: [],
myObGroups: [],
myObjects: []
}
});
script.js
Q.all([LoadData.GetUsers($http), LoadData.GetObGroups($http), LoadData.GetObjects($http)]).then(function () {
console.log(_gl.myUsers);
console.log(_gl.myObGroups);
console.log(_gl.myObjects);
});
The problem is, the Q.all won't wait till all http request will get the data, it evaluates calls in then before it happens. Sure, I could use some timer and just wait for a second, but I want more proper way to do that, please share with your knowledge.
And one more thing, if I use forEach in then of my get methods then arrays filling all right, but other arrays are empty and I want to know why it happens.
Thank you.
You have to return the promises in GetUsers, GetObGroups and GetObjects, otherwise Q.all can't do its job.
Therefore, e.g.:
GetUsers: function ($http) {
return $http({
....
should do the trick.
I'm learning AngularJS, and trying to post dump data to the php backend using the coding below.
angular.module('app.customerModule', [])
.factory('customerFactory', function($scope, $http) {
return {
var customer = {customer: '1234'};
httpNewCustomer: function(callback) {
$http.post('http://domain.local/customer_new.php', )
.success(function(data) {
})
}
}
})
.controller('customerController', function($rootScope, $scope, customerFactory) {
$scope.newCustomer = function() {
customerFactory.httpNewCustomer(function(dataResponse) {
});
}
});
Unfortunately at the server side gets nothing for $_POST;
This is what the http header looks like.
I also tried with this alternative coding
httpNewCustomers: function(callback) {
var postData = {customer: '2345'};
$http({
method: 'POST',
url: 'http://domain.local/customer_new.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}
})
.success(function(data) {
})
}
This is what the http header looks like.
When I tried with jQuery using this coding, everything is just fine.
var postData = {customer: '3456'};
$.ajax({
type: 'POST',
url: 'http://domain.local/customer_new.php',
dataType: 'json',
data: postData,
success: function(data) {
// console.log(data);
}
});
Please help me config the $http to post the data to the php backend.
angular by default only supports a json request transformer. as you can see, both your angular requests have data, but they are json. You either need to change the server so it can parse json, or add a request transformer so the data is in form-encoded format.
You can read more about $http transformers here: https://docs.angularjs.org/api/ng/service/$http
I'm using external mongodb and wrote a node/express server for fetching the data on my localhost.
I query localhost like this:
http://localhost:8888/api/bonsais
And I'm getting the correct results from my mongodb collection # mongolab.
[{"name":"test,test2","_id":"536be2e2ae54668818000001","__v":0},{"name":"testname","_id":"536fd2df41f84a581c000001","__v":0}]
I wrote a service to fetch the data like this:
angular.module('bonsaiService', ['ngResource']).
factory('bonsaiService', function($resource) {
return $resource('http://localhost:8888/api/bonsais',{'query': {method: 'GET', isArray: true }});
});
I'm getting a Error: [$resource:badcfg] object, which is referring to these error docs
.factory('Bonsai', function($q, $resource){
var bonsaiResource = $resource('http://localhost:8888/api/bonsais', {}, {
get: {
method: 'GET',
isArray: true
}
});
return {
get: function() {
var q = $q.defer();
bonsaiResource.get({
},
function(resp) {
q.resolve(resp);
}, function(httpResponse) {
q.reject(httpResponse);
});
return q.promise;
} };
})
try to write it this way.
Then you can call it with Bonsai.get()
Thanks #thesearentthedroids, your responds fixed it for me!
Just to follow up, I've used the following to retrieve the data in my controller:
bonsaiService.get($scope.trees).then(
function(data){
$scope.trees = data;
});
I have an Angular service/provider that serves json data to my controller which works great:
angular.module('myApp.services', ['ngResource']).
factory("statesProvider", function($resource){
return $resource('../data/states.json', {}, {
query: {method: 'GET', params: {}, isArray: false}
});
});
But I also need to serve json data to the same controller from another file counties.json.
Where can I find out how to I write a service that serves both files to my controller?
You can update service to return a hash of resources, not a single one:
angular.module('myApp.services', ['ngResource']).
factory("geoProvider", function($resource) {
return {
states: $resource('../data/states.json', {}, {
query: { method: 'GET', params: {}, isArray: false }
}),
countries: $resource('../data/countries.json', {}, {
query: { method: 'GET', params: {}, isArray: false }
})
};
});
You will be able to use it adding .query() at the end your function name i.e. geoProvider.states.query() and geoProvider.countries.query() and myApp.services has to be injected into your controller, then inject geoProvider service into controller itself as well.
I'm assuming you want to execute some code when both files have loaded. Promises work really well for this. I don't think resources return promises, but you can use the $http service for simple ajax calls.
Here I define one service each for the two data files, and a third service that returns a promise that gets fulfilled when both files are done loading.
factory('states',function($http) {
return $http.get('../data/states.json');
}).
factory('countries',function($http) {
return $http.get('../data/countries.json');
}).
factory('statesAndCountries', function($q, states, countries) {
return $q.all([states, countries]);
});
Then in your controller:
statesAndCountries.then(function(data) {
var stateData = data[0];
var countryData = data[1];
// do stuff with stateData and countryData here
});