loading multiple JSON files in AngularJS - html

I have two different JSON files and they have the same attributes in them. I'm able to load them by using two promises in my service but when I go in my HTML and try to display my data they display the same thing.
This is my service:
$http.get("data.json");
//User JSON api
$http.get("data1.json")
.then(function (response) {
dataRecievedCallback(response.data);
}
Should I assign my $http.get to a variable, if yes How can I do that and do I need to change anything in my controller?
I haven't been coding for long and I'm new to angular so all the help is appreciated.

$http.get("data.json")
.then(function (response) {
$scope.foo = response.data;
}
$http.get("data1.json")
.then(function (response) {
$scope.bar = response.data;
}
Not sure about your "dataRecievedCallback()" function, if your function set the data into the same variable, the second $http call will overwrite the first one.

Related

Trouble with loading json files into template.html using angular factories

I am trying to understand how to use factories and struggling to understand a few things.
I want to load json file into template but I am hitting the wall
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
myApp.factory('Tester', function($resource) {
return $resource('users.json');
});
myApp.controller('PersonCtrl', function ($scope, Tester, getUsersFactory) {
// Teens are from static json file
$scope.users = Tester.query();
// Adults are from REST API
$scope.teens = getUsersFactory.query();
});
If you will have look in my example you will see that I am trying to load from users.json file content to main.html
I would like to be able to load multiple json files into main.html
PLUNKER example here
Could you please advice me with example how to do this correctly.
You need to change your getUsersFactory factory, because you don't have there $scope:
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(searchStr, callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ searchStr}).success(callback);
}
}
}]);
As you can see, i added one more parameter - searchStr.
You need to call function getUsers() of your factory getUsersFactory. Actually problem is next: function query() is not defined in your factory getUsersFactory.
Actually seems it works even if call $scope.teens = getUsersFactory.getUsers(); - without params.
So, answer to your question - use function of factory which you defined: getUsersFactory.getUsers()
Changed plunk: http://plnkr.co/edit/xIzd8Zyg0hzMgbPCzEfj?p=preview

AngularJS - $http.post send data as json

I'm working on autocomplete directive with angularjs but having some issues.
I have a form which have an autocomplete input. When i type something there, the term variable is sent as JSON:
But, when i use the same function (from different angular controller, but the same function) in another form the term variable sent perfectly and the autocomplete works fine:
Here is my angular function:
$scope.getCustomers = function (searchString) {
return $http.post("/customer/data/autocomplete",
{term: searchString})
.then(function (response) {
return response;
});
};
What do you think is wrong?
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
$http.post(url, parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Angularjs $resource and $http synchronous call?

I want write two services one with a $http.get method and one with $resource
This service should receive a Json Object and looks like this, at the moment this code is direct in my controller and not in a service:
var csvPromise= $http.get(base_url + 'DataSource/1').success(function(data) {
$scope.data4=JSON.stringify(data);
});
The problem is, I want save received data in $scope.data4 and I want use this data after the $http.get call but the value is empty.
Direct after this call there is and Object that needs this value:
new myObject($scope.data4)
so myObject must wait so long until the data has arrived.
or can I make a synchronous call with $http or $resource ?
How can i do this ? I have found so many examples with promise and .then but nothing has worked for me.
EDIT: I have now written a service but it didn`t work:
var test=angular.module('myApp.getCSV', ['ngResource']);
test.factory('getCSV',function($log, $http,$q, $resource){
return {
getData: function (id) {
var csvPromise= $http.get(base_url +'DataSource/'+id)
.success(function(data) {
return data;
});
return csvPromise;
}
}
});
and then in my controller I call this:
getCSV.getData(1).then(function(theData){
$scope.data4=JSON.stringify(theData);
new myObject( $scope.data4); });
but this did not work. I thought if the $http.get receives the data then the then Function is called.
I don't believe you can do synchronous calls. That said, you have at least two options:
1) Pass in the data using the $routeProvider resolve feature. From the documentation:
An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected
An example on how to use this:
$routeProvider
.when('/your/path', {
templateUrl: '/app/yourtemplate.html',
controller: 'yourController',
resolve: {
data: ['$route', '$http', function($route, $http) {
return $http.get(base_url +'DataSource/1');
}]
}
})
And then in your controller:
app.controller('yourController', ['$scope', 'data', function($scope, data) {
$scope.data4 = JSON.stringufy(data);
var yourObj = new myObject($scope.data4);
}]);
2) The second option is to use promises and only instantiate your new myObject($scope.data4) once the promise successfully completes.
Your code needs to be changed just a bit:
$scope.data4 = '';
var csvPromise= $http.get(base_url +'DataSource/1');
csvPromise.then(function(data){
$scope.data4 = JSON.stringify(data);
}, function(data){
//error handling should go here
window.alert(data);
});
This should give you what it sounds to me like you need.
As i know, there's no way to sync~ call the http or resource. They're hard coded on AngularJS core file :
xhr.open(method, url, true);
And you don't want to hurt your users too by blocking the browser wait the data arrived. You'll better show how you make the nothing has worked for me so we can start working to fix it.
Have you try call new myObject($scope.data4) inside success method?
$http.get(...).success(function(data){
$scope.data4 = JSON.stringify(data); // I've no idea why do you need this.
var stuff = new myObject($scope.data4); // THis is now your.
});

Get JSON data with AngularJS and add methods on the returning object

I need to get some JSON data from the server with Angular. Let's say the user data. I created a service like that:
app.service('User', function($http) {
retrun $http({method: 'GET', url:'/current_user'});
});
And in my controller:
app.controller('SomeCtrl', function($scope, User) {
User.success(function(data) {
$scope.user = data;
});
});
That works just fine but what if I want to add some methods to the user? For instance in the view I would like to do {{user.isAdmin()}}. Is it the correct approach? Where can I add those methods?
If you wanted your service to always return an object with this method, do something like this:
app.service('User', function($http) {
return $http({method: 'GET', url:'/current_user'}).
then(function(response) {
response.data.isAdmin = function() { return true; };
return response.data;
});
});
Now any future code that references this promise and uses .then() will retrieve the new object. Take a look at the promise documentation for more information.
http://docs.angularjs.org/api/ng.$q
Keep in mind by using 'then' on an httpPromise it will be converted to a normal promise. You no longer have the convenience methods 'success' and 'error'.
It may be better practice to create a class for the object you are returning with a constructor function which takes the data object and assigns appropriate properties (or extends the instance). This way you can simply do something like
return new User(val);
And you will get all of the methods you want (with a prototype, etc).
You can do this in a few ways in the service you created:
Start using $resource and use a transform on the response:
http://jsfiddle.net/roadprophet/prtAP/
...
transformResponse: function (data, headers) {
data = {};
data.coolThing = 'BOOM-SHAKA-LAKA';
return data;
}
...
I recommend this method because it scales cleaner due to the use of $resource.
Setup a transformResponse with $http:
http://jsfiddle.net/roadprophet/bPfcz/
Use your own promise that resolves after the get promise resolves but with the mapped data. This is probably the most manual way to handle it since it requires you to manage multiple promises.

Angularjs - Update JSON

I'm very new to Angularjs and am having issues figuring out how to update a $scope element I created from JSON. Basically I have a service that contains the function which grabs the JSON:
app.service('JSONService', function($http){
return{
getJSON: function(){
return $http.get('posts.json')
.then(function(response){
return response.data;
});
}
};
});
I then have a Controller that contains a function that gets the JSON data on button click and puts it in $scope.data and a second function that I would like to use to update $scope.data:
app.controller('PostController', function PostController($scope, JSONService){
$scope.data;
$scope.getJSON = function(){
$scope.data = JSONService.getJSON();
};
$scope.addPost = function(){
// Add to $scope.data
};
});
Currently, I successfully grab the JSON data and am able to use it to populate aspects of my view, but I am stuck on how to proceed with updating $scope.data so that:
It actually updates
The update is reflected in my view
I have tried $broadcast, $scope.data.push, $scope.data.posts.push. These have either flat out not worked or given errors. I'm sure it might be a simple answer, but I feel I may be inexperienced with Angularjs and JSON to pick up on it. Thanks in advance.
So I think there are a couple issues with the code above. Hopefully this can help you get it straightened out:
The $http.get() function returns a "promise". Promises have a then() function, which you are using, but you should probably adjust to take the data that gets returned and put it straight into $scope. Doing a "return" statement inside the then() in your service does not really have anywhere to go at that point since the request was async. Angular knows how to work with promises, so you can bind to the data in the UI, but you will actually not find the data directly under $scope.data. $scope.data will still be a promise object, and the data will be in another property (something like $scope.data.promiseData -- don't remember exactly what the property is though). You could adjust like this:
app.service('JSONService', function($http){
return {
getJSON: function() {
return $http.get('posts.json');
}
};
})
Controller:
app.controller('PostController', function PostController($scope, JSONService){
$scope.data;
$scope.getJSON = function(){
JSONService.getJSON()
.then(function (response) {
$scope.data = response.data;
});
};
$scope.addPost = function(postText){
// Add to $scope.data (assuming it's an array of objects)
$scope.data.push({postText: postText});
};
});
HTML:
<div data-ng-repeat="post in data">{{post.postText}}</div>
<input type="text" ng-model="newPostText">
<button type="button" ng-click="addPost(newPostText)">Add Post</button>
Actually, whilst the above code is correct, in this case, the getJSON function isn't actually called anywhere, so the $scope.data is never populated.