PUT and POST Angularjs - 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.

Related

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

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;
},

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.

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.

AngularJS : How to inject a service into a factory

I have a REST backend which provides a hashmap of API methods. This allows the front end to use a keyname to map to the API method instead of needing to know the entire REST url.
Ex:
{
CHARGE.GET_CHARGE_INFO: /provider/charge/getChargeInfo/{{providerId}}/{{chargeId}}
CHARGE.LIST_CHARGES: /provider/charge/listCharges/{{providerId}}
CHARGE.LIST_TYPES: /provider/charge/listTypes
}
There is a service which is responsible for loading the hashmap from the REST API.
app.service('preloader', function ($http, globals, $interpolate, $q) {
var self = this;
var endPointsList = $http.get(globals.apiPath + globals.endPointsPath, {}).success(function (data) {
self.endPoints = data;
});
return {
endPointsList: endPointsList,
getResourceEndPoint: function( endPoint ){
if (!self.endPoints[endPoint]) {
// To avoid misleading errors
throw ("Endpoint not found. \r\nEndpoint: " + endPoint + "\r\nFound: " + self.endPoints[endPoint]);
}
// reformat
return globals.apiPath + self.endPoints[endPoint].replace(/{{([^}]+)}}/g, ":$1");
}
};
I'm trying to write a $resource which uses this service, but the problem is when the service is injected into the factory, it has not yet been initialized and consequently calls to the method to retrieve the endpoint throw errors.
app.factory('providerFactory', ['$resource', 'preloader',
function ($resource, preloader) {
return $resource( "", null,
{
"getTypes" : {
method: 'GET',
url: preloader.getResourceEndPoint('PROVIDER.LIST_TYPES')
},
"get": {
method: 'GET',
url: preloader.getResourceEndPoint('PROVIDER.GET_PROVIDER_INFO'),
params: {
providerId: '#providerId'
}
}
}
);
});
Error Msg:
TypeError: Cannot read property 'PROVIDER.LIST_TYPES' of undefined
at Object.getResourceEndPoint (http://localhost:8888/client.git/build/app.min.js:3:8967)
If I step through the code, I see that the factory's preloader.getResourceEndPoint() calls are calling the service before the service has completed its initialization of the endPointsList.
What can I do to avoid this problem? Do I have to use a $q promise? It seems like overkill for something like this. If so then I have to wonder if this is even the right approach to get something like this to work, but I'm not sure what approach to use.
I'm still learning AngularJS so I'm not entirely sure of the correct way to proceed. Ive inherited this code so if it seems that it is convoluted/complicated for nothing, I'd appreciate insights on how to improve it.

Preserving scope across routed views

I have a SPA with a list of Clients displayed on the landing page. Each client has an edit button, which if clicked should take me to an Edit view for that selected Client.
I'm not sure how to go about this- all the routes I've seen so far will just take my client id in the $routeParams, and then most examples will then pull the Client from a factory by that Id.
But I already HAVE my Client... seems a waste to hit my web api site again when I already have it. Is it possible to route to the new view and maintain the selected Client in the $scope?
Edit:
This is what I did- I don't know if it's better or worse than Clarks response... I just made the following angular service:
app.service('clientService', function () {
var client = null;
this.getClient = function () {
return client;
};
this.setClient = function (selectedClient) {
client = selectedClient;
};
});
And then for any controller that needs that data:
$scope.client = clientService.getClient();
This seemed to work fine... but would love to hear how this is good or bad.
Depends on what level of caching you want.
You could depend on browser caching, in which case proper HTTP headers will suffice.
You could depend on cache provided by $http in angular, in which case making sure the parameters you send up are the same would be sufficient.
You could also create your own model caching along the lines of :
module.factory('ClientModel', function($http, $cacheFactory, $q){
var cache = $cacheFactory('ClientModel');
return {
get : function(id){
var data = cache.get(id);
if(data){
//Using $q.when to keep the method asynchronous even if data is coming from cache
return $q.when(data);
} else {
//Your service logic here:
var promise = $http.get('/foo/bar', params).then(function(response){
//Your model logic here
var data = response;
cache.put(id, data);
return response;
}, function(response){
cache.remove(id);
return response;
});
//Store the promise so multiple concurrent calls will only make 1 http request
cache.put(id, promise);
return promise;
}
},
clear : function(id){
if(angular.isDefined(id)){
cache.remove(id);
} else {
cache.removeAll();
}
}
}
});
module.controller('ControllerA', function(ClientModel){
ClientModel.get(1).then(function(){
//Do what you want here
});
});
module.controller('ControllerB', function(ClientModel){
ClientModel.get(1).then(function(){
//Do what you want here
});
});
Which would mean each time you request a client object with the same 'id', you would get the same object back.

Resources