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

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

Related

loading multiple JSON files in AngularJS

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.

Consuming JSON string array, returned by a webservice, in AngularJS

There is a Webservice that is returning a json object in below format:
["Brazil","Argentina","Chile"]
(this json object has been parsed by Online JSON parsers, which proves it is a proper json object)
In AngularJS, I wrote the below code to consume the WebService.
app.factory('webServiceFactory', ['$http', function ($http) {
return $http.get('http://SomeWebService/api/anOperation')
.success(function (data) {
return data;
})
.error(function (err) {
return err;
});
}]);
When I call this in my controller, the success part is never hit and, instead, the error part is executed. That means there is some error calling the web-service. I think it has to do something with the JSON object that is being returned.
Edit 1: The Controller code
app.controller('mainController', ['$scope', 'webServiceFactory', function ($scope, webServiceFactory) {
webServiceFactory.success(function (data) {
$scope.Countries = data;
});
}]);
Edit 2: Localhost & CORS
When I hosted the service in my local IIS and consumed it using localhost, it worked. That means there is no error in consuming the JSON String array.
However, when I use a Fully qualified name or machine name, the FireFox indicates CORS header missing 'Access-Control-Allow-Origin'.
This might lead to another question, as to how to make it CORS compatible. However, the main question is closed.
So, my question, is How do I consume a web-service in AngularJS that returns just an array of strings with no Key/Value pair?
Thanks
maybe you are doing a request to a service in other domain; that is not possible since exists the "same origin policy" https://www.w3.org/Security/wiki/Same_Origin_Policy
app.factory('webServiceFactory', ['$http', function ($http) {
return
{
getCountries: function(callback){
$http.get('http://SomeWebService/api/anOperation').then(function(reponse){
callback(response.data);
});
}
};
}]);
Then in your controller
webServiceFactory.getCountries(function(countries){
$scope.countries = countries;
});

angularjs $http query params not working

I have this plunker
http://plnkr.co/edit/ml1Eqvz5pZY1MgxX87s7?p=preview
i am trying to query the .json file with no success. here is my factory
app.factory('myService', function($http, $q) {
return {
getFoo: function() {
var deferred = $q.defer();
$http({ url: 'foo.json',
method : "GET",
params : { 'item.id' : 0 } })
.success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
},
}
});
it works well but it doesn't get only the id:0. I want not to load all data from the .json file. I want to load only what's in id:0
any pointers?
thank you
What you have is a static JSON file. You can add every parameter you want to the request, if there is no dynamic component at server-side to interpret these parameters and serve what you want to serve, sending parameters is useless: the server receives a request for a static JSON file, and it serves the static JSON file.

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.