how to use $resource to get the data from local json file - angularjs

I am trying multiple ways to access my users in a local json file in able to later compare them to the users input. and if there is a match, access is allowed, but my main problem now is just getting to those users.
My code so far:
entire code
json file
What am i doing wrong? i am such a newbie in programming. I have been trying different things and nothing works.
Thanks so much for help

Can you access the file through the browser (via your url localhost:8080/resources/data/users.json)?
If you can't, you will not be able to get access through the $resource or $http.
If you can, any method should work:
1) Via $resource
$scope.users = [];
var UsersResource = $resource('/resources/data/users.json');
where we can get response by callback
UsersResource.get({}, function(response) {
$scope.users = response;
});
or by $promise
UsersResource.get().$promise.then(function(response) {
$scope.users = response;
});
2) Via $http.get
$scope.users = [];
$http.get('/resources/data/users.json').then(function(response) {
$scope.users = response;
});
In your sample, your are trying to get array of users by returning $resource, but $resource returns a object with methods. Each method has callbacks (success, error) or return $promise object.

There is no need to use $resource if you are just going to fetch a json file. Use $http instead:
this.getUsers = function(){
return $http.get('path/to/file.json');
};
And usage:
dataService.getUsers().then(function(resp){
//Do something with the data
$scope.users = resp;
})
$resource is meant to be used when communicating with RESTful apis. What your getUsers() is doing is actually returning a resource-object, upon which you can then call get(). But I recommend using $http in this case.

If you want to use $resouce then you need to create two functions in your controller/factory where "templatesSuccess" return data of request.
getAllTemplates: function(query) {
return $resource(CONST.CONFIG.BASE_URL + 'receiver/get-templates').get(query, obj.templatesSuccess).$promise;
},
templatesSuccess: function(response) {
obj.allTemplates = response;
},

Related

Returning one object with the result of two AJAX GET calls

I'm working on a simple weather app that will grab both the current and the weekly forecast from a weather API. To keep it simple, I'd really like to my weatherService function, getForecast, to somehow make two AJAX calls -- one for the weekly forecast, which I already have, and one for the current forecast (unfortunately I don't think this API has a means of retrieving a JSON return that contains both). I'm not sure about the best way to go about doing this, I'm very new to Angular.
Here's my service:
weather.service('weatherService', function($resource, $http){
this.currentForecast = null;
// default city
this.city = 'Chicago, IL';
this.getForecast = function(location, type) {
return $http({
method : "GET",
url : "http://api.openweathermap.org/data/2.5/forecast/daily?q="+location+"&mode=json&cnt=7&appid=e92f550a676a12835520519a5a2aef4b"
}).then(
function(response) {
return response.data;
}
)
};
});
And I'd like a second GET, retrieving from: http://api.openweathermap.org/data/2.5/weather?q=Chicago,IL&appid=e92f550a676a12835520519a5a2aef4b to be appended to the response, so that there's a single object returned.
Also, if this isn't the best way to go about doing this, I'm certainly open to suggestions.
What you are looking for is angular promises library $q
$q.all([$http(...), $http(...),...]).then(function(ret){
// ret has all results from all ajax calls
})
More specifically:
weather.service('weatherService', function($resource, $http, $q){
this.getForecast = function(location, type) {
return $q.all([
$http.get(url1(location, type)),
$http.get(url2(location, type))
])
}
})
...
weatherService.getForcast(location, type).then(function(ret){
console.log(ret[0].data)
console.log(ret[1].data)
})
There is excellent video on using $q.all at egghead.io
Well, you could use webworkers, but then you have 6 problems. You can also chain requests using then callbacks.

How can I parse this JSON response

I have the following JSON data being received by angularJS. It's being brought in from an ArrayList using a get request.
0: Object
id:1
area: "State"
gender: "Both"
highestEd: 3608662
.... etc
1: Object
id:2
area: "State"
gender: "Both"
highestEd: 3608662
.... etc
However I can't figure out how to access it using either a controller or the UI. I want to be able to store this data in Angular so I can then create graphs using the information. The only way I know it's definitely there is through looking at the response in firefox.
Any help / advice would be greatly appreciated.
Your JSON data is not in proper format. Use JSON lint to check
Use $http.get('/get_url/') to get the response . One sample example for this.
Once you have response in $scope.yourVariable use ng-repeat to loop over it
Take a look at this fiddler here you might get some ideas.
After calling the API using $http from you factory you will have resolve the data that you are getting. The controller needs to call the API method and then bind the resolved data from your factory to the API.
Factory
myApp.factory("Data", function($q, $http) {
return {
getData: function() {
var deferred = $q.defer();
/* --Actual API Call
$http.get("/url")
.then(function(response) {
deferred.resolve(response.data);
})
*/
//Dummy Data
var data = m;
deferred.resolve(data);
return deferred.promise;
}
}
});
Controller
function MyCtrl($scope, Data) {
Data.getData()
.then(function(items) {
$scope.bobs = items;
console.log($scope.bobs);
})
}
Replace the dummy data initialization from factory to the actual API call.

Retrieving data using $http.post

Hi I want to get data from my json file using post method(which is working 5n with get method)
'use strict';
angular.module('myapp').controller('lastWeekWinners',function($http){
var vm= this;
$http.post('http://localhost:9000/json/sample.json').then(function(data){
vm.winnerData=data.data.data;
},function(error){
console.log(error);
});
});
the about code is give error
which means can't we use post method to get the data
This is how u can use the post method in your controller:
'use strict';
angular.module('myapp').controller('lastWeekWinners', controller){
function controller($scope,fetch){
var vm= this;
vm.show = show;
}
function show() {
return fetch.show()
.then(function successCallback(data){
vm.winnerData = data;
}
}, function errorCallback (response) {
console.log(response.statusText);
});
}
});
and in your service :
angular
.module('service',[])
.service('fetch', Service);
function Service($http) {
var fetch = {
show : show
}
return fetch;
function show() {
return $http.get('http://localhost:9000/json/sample.json')
.then(getShowComplete)
.catch(getShowFailed);
function getShowComplete(response){
return response.data;
}
function getShowFailed(error){
console.log("Error:" + error);
}
}
First of all, the difference between GET/POST:
GET is used for getting data, POST is used for saving (and sometimes updating) data. So if you just want to get the json, use GET.
Regarding the specific problem you have here, if you look carefully, you get a 404 code. that means the route was not found. (You can read more about HTTP status code here: http://www.restapitutorial.com/httpstatuscodes.html)
Not sure what server you're using but usually, you're not only defining a route but also the verb of the route (GET/POST/PUT/DELETE), so if you have a route defined like:
GET /users/
This will only work for GET requests, if you try to post for the same route you'll get 404. You have to define the same route for the POST verb.
You can read more about http verbs here: http://www.restapitutorial.com/lessons/httpmethods.html
To do $http.post you need a back end API(PHP,Node Js etc),that system catch your desired post data and save into the db or JSON(Read/Write Method).
Static JSON data just read only possible not write.
Or used Browser $window.localStorage to save data.

PUT and POST Angularjs

I have an Ionic project with a WCF RESTful service, I want to be able to Insert and Update data. I can already view data with GET method but can't find anything on the internet for PUT and POST. How would I be able to accomplish this?
GET Method
$scope.selectedDist= function() {
$http.get("http://192.168.1.113/Service1.svc/GetAllComp")
.success(function(data) {
var obj = data;
var ar = [];
angular.forEach(obj, function(index, element) {
angular.forEach(index, function(indexN, elementN) {
ar.push({CompID: indexN.CompID, CompName: indexN.CompName});
$scope.districts = ar;
});
});
})
.error(function(data) {
console.log("failure");})
};
Post methods I tried
#1
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http.post("http://192.168.1.113/Service1.svc/GetAllComp", ar)
.success(function(data)
{
console.log("data inserted successfully")
})
.error(function(data)
{
console.log("Error")
})
#2
$scope.insertdata = function() {
var ar = [{'M1':$scope.M1, 'M2':$scope.M2,'M3':$scope.M3,'M4':$scope.M4,'M5':$scope.M5,'M6':$scope.M6,'M7':$scope.M7,'M8':$scope.M8,'M9':$scope.M9,'M10':$scope.M10,}]
$http ({
url : "localhost:15021/Service1.svc/TruckDetails" ,
Method : "POST" ,
headers : {
'Content-Type' : 'Application / json; charset = utf-8'
},
Data : ar
})
Also Would I need to make a POST or PUT method on my Service as well or can I use the GET methods?
You can use a get method, in combination with a querystring to post and put data but that is not what it was designed for and should be avoided for several reasons such as security.
That being said, it is not that difficult to use post and put in angular and in the following , rather naive service , you can see all that is required to do is passing your data in the service function you're invoking.
.service('MyService', function($http) {
this.postMethod = function(data) {
return $http.post('http://my.url', data);
};
this.putMethod = function(id, data) {
return $http.put('http://my.url/' + id, data);
};
}
So that in your controller you can inject and invoke the service methods with the $scope data that needs to be stored.
After taking a look at your attempts you seem to be using the same url for both get and post: "http://192.168.1.113/Service1.svc/GetAllComp" which actually leads me to believe you haven't thought about implementing these methods on your server. Can you confirm this?
Apart from that, it is always usefull to look at statuscodes when trying to send requests because they provide a great deal of information about the nature of the error that occurs. You can investigate that in either your console or an external program such as Fiddler.
P.S.
Deprecation Notice The $http legacy promise methods success and error
have been deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.

angular-http-auth with $http transformResponse

I'm using angular-http-auth to show a login dialog whenever a 401 "unauthorized" response is returned from the server.
Since I'm cool, I also try to deserialize response objects in my services. For example, if a service requests a car and the response is {make: Honda, model: Civic}, I try to deserialize that into a Car object using transformResponse.
For example:
getCar: function() {
return $http.get('/api/car', {
method: 'GET',
transformResponse: function(data, headers) {
var c = angular.fromJson(data);
return new Car(c);
}
});
}
This doesn't work with angular-http-auth. If the response was a 401 Unauthorized, you'll get a javascript error. It's because angular will try to run that transformResponse code even if the response was a 401.
It turns out that $http interceptors (which is what angular-http-auth uses) are run AFTER the transformResponse code. That's a huge problem, because none of that code in transformResponse will work if the server response was a 401 (there wouldn't be any data)
Is this a problem for anyone else? How did you get around it? Am I not to use transformResponse if I use $http interceptors?
Late to the party, I know, but to anyone coming here from Google like I did (I also posted this as a comment on a related issue filed with the Angular repo):
I also found it to be confusing that response interceptors run after the transformResponse method. I added a method to $http.defaults.transformResponse. Here is an example from the documentation on how to do that.
So, if you need to basically have a response interceptor that runs before the transformResponse method, this should do it:
'use strict';
angular.module('app')
.run(function ($http) {
$http.defaults.transformResponse.push(function (data, headers) {
// do stuff here before the response transformation
// Be sure to return `data` so that the next function in the queue can use it.
// Your services won't load otherwise!
return data;
});
});
If your services or http calls don't have their own response transformer, you're good now.
If your services do have their own transformResponse method, they will actually override all default transformers (I found this out after a long read of the documentation), and the above code will not run.
To circumvent this, you can follow this example in the docs.
To get around this problem I don't use transformResponse anymore. I just can't see the point of transformResponse if it runs before $http interceptors.
In order to use angular-http-auth and also deserialize responses in your services, you can write your services so that they execute the HTTP request first and then deserialize the response in a callback function.
As an example, here is how I would have restructured the example in the OP:
Plunker
services.factory('HttpCarService', function($resource, $q) {
var resource = $resource('/api/car');
return {
getCar: function() {
var deferred = $q.defer();
var car = null;
var successCallback = function(data, status, headers, config) {
var c = angular.fromJson(data);
car = new Car(c);
deferred.resolve(car);
};
var errorCallback = function(data, status, headers, config) {
deferred.reject("something wrong");
};
var result = resource.get(successCallback, errorCallback);
return deferred.promise;
}
};
});
This pattern will also work if data is an array.
$http interceptors will run before either of the callback methods are executed. If your $resource needs url params, you can make the getCar() function accept a config object as a parameter, and pass the necessary information on when you make the $resource.get() call.

Resources