I have just started exploring AngularJS. Is there any way by which I can extract the original JSON returned from server?
I am trying to get some data using $resource.get from a WebAPI. The returned promise contains some additional properties compared to my original JSON.
When I assign this object (returned from $resource.get) to some of my Javascript controls (like DHTMLX Scheduler), it does not work correctly but if I use $http it returns pure JSON and the control works perfectly.
I am more interested in using $resource as it has been used in the rest of the Angular controllers.
Let's say you have a service that's defined using a resource:
app.factory('LoginService', function($resource, API_URL) {
return $resource(API_URL + '/login.json');
});
Then elsewhere in a controller (for example) you want to use that service:
var loginRequest = LoginService.get({
email: email,
password: password
}).$promise;
loginRequest.then(function onSuccess(response) {
// access data from 'response'
var foo = response.foo;
},
function onFail(response) {
// handle failure
});
The key is that you need to access $resource.get().$promise, not $resource.get().
Related
I am trying to create 'Order' object in the front end and pushing it into the database using REST services. POJO of 'Order' looks like below
#NotNull
#Field("total")
private BigDecimal total;
#Field("status")
private String status;
#Embedded
public User user;
Now I have a 'Principal' service which is providing information of the currently logged in user.I have tried 'console.log(Principal.identity())' which is returning result as shown below. Here 'User' data is present inside the '$$state' Object.
I am not able to find out how to take 'user' data from promise object and add to the 'Order' object. I have dirty method to get user data by digging inside the Promise object as shown below but I am skeptical about this method.
What is the correct way to get data from Promise in this scenario?
EDIT:
This is jhipster based application. Below is the "Principle" service code
'identity: function (force) {
var deferred = $q.defer();
if (force === true) {
_identity = undefined;
}
// check and see if we have retrieved the identity data from the server.
// if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
.then(function (account) {
_identity = account.data;
_authenticated = true;
deferred.resolve(_identity);
Tracker.connect();
})
.catch(function() {
_identity = null;
_authenticated = false;
deferred.resolve(_identity);
});
return deferred.promise;
}'
Here is the jhipster generated method to receive resource from server using ngResource.
'angular.module('hotSpiceApp')
.factory('Order', function ($resource, DateUtils) {
return $resource('api/orders/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
},
'update': { method:'PUT' }
});
});'
The Principal.identity() function returns a Promise. First read what is promise.
Then do something like:
Principal.identity().then(function (user) {
var data = {
// other fields
user: user
};
// do something with data only inside this inner function
});
Doing Principal.identity().$$state.value is bad not only because it related on internal implementation of angular's promises but it also won't work in all cases. Promises by nature is asynchronous and this work only because Jhipster caches result of http request which returns current user. But if there are no info about current user at time of your new requst, then Principal.identity().$$state.value will be undefined because first it need to send http request to the server and only after that this promise will be "resolved" (internally it will set the value variable and call function defined in then method).
Also I should note, that you should not pass current user from JS code to the server. You should take current user on server side (from session or something) after request arrived and set it to your model if needed. Never trust user code (code which runs in user's browser). It can inject any value to this request and send it to the server.
Can you explain the way you are retrieving the principal service? If it is returning a promise you need to set the data you want to a local variable in the "then" method.
Now to see what "Principal" service has , you can use the below code in chrome console
angular.element(document.querySelector('html')).injector().get(Principal);
I am working on a project using Parse.com rest api and Ionic/angularjs.
When I issue a Post request, I would like to get the objectId from the Response body.
I can see that the objectId is included in the response in json format, but I canĀ“t seem to extract it.
var signUp = new SignUp(signUpData);
var response = signUp.$save(); // using angularjs $resource
console.log(response);
When I log the reponse I get this in the console: Object { $$state: Object }
"Dotting" into $$state only returns a number.
Any help would be appreciated.
I never used Parse.com but if you are using $resource code below should works
var signUp = new SignUp(signUpData);
signUp.$save(function(response){
console.log(response);
});
I'm new to Angular and also relatively new to the JSONP format. In my code, I set up a factory to read in the JSONP file - and I get back the data variable as the JSONP data properly
$http.get('someJSONFile').success(function(data){
console.log(data);
});
The console log gives me back the following:
states([{"code":"AL","name":"Alabama"},{"code":"AK","name":"Alaska"},{"code":"AZ","name":"Arizona"},{"code":"AR","name":"Arkansas"},{"code":"CA","name":"California"},{"code":"CO","name":"Colorado"},{"code":"CT","name":"Connecticut"},{"code":"DE","name":"Delaware"}])
So - I'm stuck on what to do now. I have a data object that contains a function. I need to parse out the JSON from this function - but not sure how to do it.
I have read in other places that I need to declare a function somewhere in my controller or factory called
function states(results)
{
// what is in results should be the JSON data I crave
}
But even if I do that, I don't think it ever executes - so I am not sure what I should do at that point to get the JSON data into an object that I can use.
The full file I am trying to parse is http://massachusettswebdesigns.com/states.json
Any help is appreciated!
Angular $http service provides a method to consume JSONP endpoints. In your case this should work:
$http.jsonp('someJSONFile').then(function(data) {
console.log(data)
});
Behind the scene, Angular will create a globally accessible function that will receive data, parse and pass further, so you don't need to worry about creating functions yourself.
What looks like your trying to do is standard JSON not JSONP, JSONP will require a callback and is only required if getting data from a different domain, ie a API service
Also the console log output you give is not valid JSON.
//init app
var app = angular.module('MyApp',[]);
//setup a factory for the data handling
app.factory("Data",function($http){
return {
getData:function(type){
return $http.get(type).
then(function(result) {
return result.data;
});
}
}
});
//in a controller 'call' the factory for the data
app.controller('main', function main($scope, Data) {
//other stuff
Data.getData('someJSONFile').then(function (data) {
$scope.jsonData = JSON.parse(data);
});
//other stuff
});
So my error was a stupid one. The JSON file was giving me the name of a custom callback I had to define. Once I did this, all worked. . . . here's the code
angular.module('locationApp')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.states = [];
$scope.cities = [];
// Function for the States callback on the JSON files provided
window.states = function (data)
{
$scope.states = data;
};
// Get the State JSON file.
$http.jsonp('http://locationinc-mapping-demo.herokuapp.com/states.json');
}]) // end of MainCtrl
var User = $resource(
'http://test/index.php'
);
var user = User.get({id:'1'});
// GET: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"baz" }
user.name = "qux";
user.$save();
// POST: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"qux"}
In this case, when you call the save() user object, properties will be replaced by those that came from the server.
But if the server responds like this:
{
"errors":{
"login":"too short",
"name":"is already using that name.",
"mail":"invalid email."
}
}
User object properties are overwritten and instead, property errors containing these mistakes will come up.
Is there a way to change the behavior of $resource? I would like to check the status of the response and, based on that, decide whether to update the properties of an object or report an error to the user.
Angular's $resource is meant to interact with RESTful web services.
In RESTful web services, if there's an error while saving a resource, you should return an appropriate HTTP status (for example, 400).
Then, you can optionally use the error callback:
user.$save(function (response) {
console.log("success!");
}, function (response) {
console.log("error");
});
For a full list of error HTTP statuses:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error
I'm switching from jquery $.ajax, which was working fine, to using AngularJS $http.put to access a restful API.
I can make an API call, but the PUT data isn't getting sent - so my API sees a PUT request with an empty data object, which should contain a JSON string -> data.values = 'a json structure'
$http.put(
$rootScope.api_url,
{
values: jsonifiedValues
},
{
headers: {
apihash: sha256hash
}
}).success(function(data,status,headers,config){
// handle success
}).error(function(data,status,headers,config) {
// handle failure
});
I've not used AngularJS's $http before, but when I dump out the data in my PHP api it's just empty. this is how I'm pulling it from the request in the PHP:
parse_str(file_get_contents('php://input'), $put_vars);
$arr_req_data = $put_vars['values'];
In my API if the apihash sent from the request doesn't match the sha256 hash built on the PUT values, it fails.
This is working in JQuery, just failing now I've switched to $http. I'm not sure why the PUT data seems to be empty.
The return value from file_get_contents('php://input') will be a JSON string (provided everything got sent), so parse_str is not the right function to handle that data.
Instead use json_decode.
Also there is no need to send jsonified values, it will just make things more complicated as you'll have to use json_decode twice.