how to write get method using ng resource - angularjs

hi in my requirement i tried to write post method using ngresource but now i want to change that into get method. can anyone help me to solve this problem. i am new to angularjs thanks in advance
$scope.clickresult = {};
var Call = $resource('../api/Home', {}, { query: { method: 'POST', isArray: true} });
$scope.click = function () {
//alert("hi");
$scope.selected = "";
var x = $('#txtSearch').val();
var _ReqObj = new Object();
_ReqObj.id = x;
_ReqObj.Meth = "CD";
// alert(x);
Call.query({}, _ReqObj,
function (response) {
if (response == '') {
// alert('no data');
window.location.replace("#/");
}
else {
//alert("daata");
$scope.message = response;
}
},
function (error) {
window.location.replace("#/");
}
);
};

Here is some initial help so you can solve your future problems on your own.
1. Use developer tools to see errors, requests and responses: https://developers.google.com/web/tools/chrome-devtools/
Open the tools from the menu or use cmd+alt+I on Mac or ctrl+shift+I on Windows.
In the "Network" tab of the developer tools you can see the communication with your server (E.g. request method = GET, response from the server). In the "Preview" tab you can see the json the server sent you. Tell me if you have problems finding this, because it is very important to find bugs in your code.
2. Use logging!
In angular you can add $log to your code and with $log.log("message", object) you can output debug messages and the current state of objects from your code. You can see the logging messages in the developer tools in the "Console" tab.
3. Read the documentation
Angular provides documentation and examples for their functions. Read this about the $resource service https://docs.angularjs.org/api/ngResource/service/$resource
Read about the difference between GET and POST method.
4. Try a simple example from a tutorial and try to adapt it to your needs
Copy a simple resource example from the internet and make it work. If that works change it step by step until it is what you need.
5. For your example:
How does your server side script work? In your question I can only see the angular code. If you want to use the GET method the server has to provide a function that reacts to GET.
The $resource service already provides a query method:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
Normally you don't need to add "{ query: { method: 'POST', isArray: true}" to your code. The query function is already there!
To send a GET request with the query function you just need:
var Call = $resource('../api/Home', {});
Now open your developer tools, go to the Network tab and then execute the function $scope.click in your website. What do you see in the Network tab? The request should be fired with "request method: GET". What is the answer from the server? The problem is maybe not in your angular code but in your server code.
Try these things and tell me if you need more help.

Related

Angular Token based Auth with CORS

I'm trying to create a cross domain request with angular 1.4.7. I'm pretty new to this topic and especially in this scenario I'm not able to find any help via google.
Environment:
I try to call from the angular app A served by www.a.com the restful api's offered by the server B served by www.b.com.
The thing im struggling over is, that I have to authorise myself a via token in the http post. This token constelation should look like:
{
"account": {
"hashcode": "somehashcode"
},
"hashkey": "somehashkey"
};
I tested the api with Postman an it works well, but I'm failing to realise it with angular.
postman successful try picture 1
postman successful try picture 2
To enable cors in my app.js:
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
}]);
An my request:
$http({
url: 'http://evori-api.azurewebsites.net/api/handshake',
method: 'POST',
data: authtoken,
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data, status) {
console.log(data + status);
}, function() {
});
Any help would be appreciated. Even if you just got an article or blog that explains how such things should be done. I know there is probably just a dumb mistake or something but it drives me crazy.
Thanks a lot.
It seems like the problem wasn't me or my api call. The source of the problem was, that the server didn't handle the OPTION call that leads each cors request.

angularjs PATCH method 404 response

WORK AROUND IS AT THE BOTTOM
Original problem
There are question like this all over the web and none of them really have answer for me. I can't get an http PATCH operation to work using angular to save my life. I've implemented $http, with shortcut $http.patch and without using the config object method:PATCH. I've used $resource by adding a custom method. And I've implemented Restangular using their patch and I'm getting the same error. I have the correct Content-Type as suggested in other posts. I think it's safe to say at this point, it's something I'm missing. I'm getting the same "404" message via postman when trying to patch. I can PUT, GET, POST, and DELETE, but not PATCH.
In the following images you can see that the resource exists for GET. But when trying to patch I get 404. Browsing to that endpoint shows the record. Which is stored in Mongodb.
Here's some code snippets:
Resangular GET:
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
Restangular Patch:
var data = {
corporiumId: $scope.newBlock
};
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.patch(data).then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
$http attempt using config object:
controller code:
httpCorporiumSrv.updateCorporiumId('/corporium-mgmnts/' + $scope.params.id, data)
.then(handleUpdateSuccess)
.catch(handleUpdateError);
service code, tried forcing the content-type header but got same result
with or without it:
function updateCorporiumId(url, data) {
return $http({
method: 'PATCH',
url: url,
data: angular.toJson(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
//transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Using the .patch shortcut:
function updateCorporiumId(url, data) {
return $http.patch(url, data, {
transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Thing is I've tried this every which way I know how. I don't even know how to start debugging any more. I'm just getting 404 on a resource that does exist. Any suggestions on what might be happening to my request would be great.
Resolution:
For anyone having this issue, if you could post the fix or what's going on here to this point or PM me that would be awesome I'd like to know. I ended up just using PUT to fix this.
Quick Restangular solution:
Build the url template for findByOne like function using Restangular.one(url, _id) where '_id', is the id of the resource you're looking for. .get() goes out and finds that one resource by said id, which you can populate dynamically however you like. Once you have the one resource with GET copy it with Restangular.copy() which is different from angular.copy as it doesn't bind 'this' to the new object. Change what needs to be changed or added in the new object and then perform a .put() on it.
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
var update = Restangular.copy(res);
// update date corporiumId
update.corporiumId = $scope.newBlock;
// submit new doc with altered value
update.put().then(function() {
console.log('updated')
});
console.log(update)
}, function(err) {
console.log('Restangular failed: ', err)
});
Also because mongo uses _id and Restangular uses id you have to add this to your module
angular.module('corporium-mgmnts').config(function(RestangularProvider) {
RestangularProvider.setMethodOverriders(['put', 'patch']);
// setRestangularFields is required for mongodb
RestangularProvider.setRestangularFields({
id: "_id"
});
});

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Combining GET and POST as get and save in AngularJS service

I've got a service that gets details for a certain user profile:
.factory('UserDetails', function($resource, $rootScope) {
return $resource('../html/app/user_details.json', {}, {
query:
{
method: 'GET',
params: {},
isArray: true
}
});
})
I'm mocking the non-existent back-end with a plain JSON file for now.
I also need to be able to update the user profile - so I need to write a POST request (probably to the same end-point).
In my controller I currently use:
UserDetails.get({}, function(data) {
$scope.profile = angular.copy(data.user_details);
});
It would be elegant to be able to write
UserDetails.save({$scope.profile}, function(data){ /* .. */});
Is there a way to extend my UserDetails service to achieve this? How would I have to modify the service declaration?
You can use angular-mock for your purpouses.
See related Stackoverflow question

angular js jsonp example dosn't works

im having trouble using the angular js jsonp function, i cant make this plunk to work:
http://plunker.co/edit/xQVBchTYOro1CB979021
can anyone help me?
With the JSONP "hack" you must make sure that the server's response contains callback's invocation. To make your example work you should change the prov.json file so it looks like follows:
angular.callbacks._0({
"id": "40796308305",
"about": "The Coca-Cola Facebook Page is a collection of your stories showing how people from around the world have helped make Coke into what it is today.",
...
})
There are many sources on JSONP, ex.: What is JSONP all about?
using a get instead of jsonp, you get the details of cokacola...
async: function(page) {
var url = 'prov.json';
var promise = $http.get(url).error(function (response, status) {
alert("fai");
}).success(function (response, status) {
alert(response.about);
}).then(function (response, status) {
return response.data;
});
return promise;
}};

Resources