angular.js and untappd API, how to send a Get request - angularjs

I'm trying to connect to Untappd API trought angular.js; the API docs says
Whenever you are making a call to the API, you MUST pass both your Client ID and Client Secret as GET params like below
http://api.untappd.com/v4/method_name?client_id=CLIENTID&client_secret=CLIENTSECRET
with angular I have done this simply controller
function UntappdController($scope,$http) {
$http.get('http://api.untappd.com/v4/user/badges/jonnyjava?client_id=XXX&client_secret=XXX').success(function(data) {
alert('ok');
}).
error(function(data, status, headers, config) {
alert('ko');
});
}
UntappdController.$inject = ['$scope', '$http'];
but it doesn't work. (I get always KO)
So I'have tried tro a RESTful service. In this way
angular.module('BadgeServices', ['ngResource']).
factory('Badge', function($resource){
return $resource('http://api.untappd.com/v4/user/badges/jonnyjava/', {}, {
query: {method:'GET',params:{client_id: 'XXX', client_secret: 'XXX'}, isArray:true}
});
});
But this doesn't works too...
What I'm doing wrong? I'm new to angular. It looks simple but I'm missing something fundamental...

The error function is passed these variables: data, status, headers, config. Check their contents - I'm sure the server has some why of specifying what went wrong.

Sorry, I forgot it! Here is what I get with the error function..
data: status:0 headers:function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}config:[object Object]
Nothing helpful...

Solved! It was a CORS problem. If anyone is interest the solutions is here.
stackoverflow-Angularjs issue $http.get not working

Related

How to create a POST request in my case?

I am trying to make a POST request via $resource object in Angular.
I have something like
(function (angular) {
angular.module('myApp')
.factory('myService', [
'$resource',
function ($resource) {
var serviceObj = $resource('http://testProject/products/', {id: '#id'},{
'createItem' : {
url: 'http://testProject/item/:id',
method: 'POST',
params: {type: ‘#type'}
}
});
return serviceObj;
}
]);
})(angular);
in my controller
//omit the controller codes…
myService.type = ‘Detail’;
myService.createItem(function(data) {
console.log(data)
});
I see stuff back from the console.log but it has the wrong data because the type is shown as ‘Name’ instead of ‘Detail’. I know api supports that and I don’t see anything wrong with my service. Can someone help me out for it? Thanks a lot!
It looks like your are getting data back,
I would try:
console.log(data.data);
Since your are returning an object from your service.

Can't get only the header in AngularJS (v1.3.15) using $resource and method 'HEAD'

In Angular (v1.2.19), I was able to do something like this in a factory :
myApp.factory('GetNumber', ['$resource',
function($resource) {
var get_headers = $resource('some/url', null, {
get_number: {
method: 'HEAD',
transformResponse: function(data, headers) {
var count = headers()['x-number'];
return count;
}
}
});
return get_headers;
}
]);
Call it from my controller like this:
$q.all({
'item1': GetNumber.get_number().$promise,
'item2': SomeOtherService.get().$promise
})
.then(function(results) {
$scope.newNumber = results.item1.value;
});
And I could get the custom header back without having to retrieve the whole header.
Now in v1.3.15, it doesn't work. I can see the header in Chrome with 'x-number' in the header, but if I put a breakpoint in Chrome on the 'var count' line, I never hit it (and I do hit it with v1.2.19).
I've verified that using $http.head works, so if I have this in my controller:
$http.head('some/url')
.success(function(data, status, headers, config) {
var count = headers()['x-number'];
$scope.newNumber = count ? count : 0;
});
I get my scoped value.
I've noticed that there aren't a whole lot of examples of people using the http 'HEAD' method and I'm wondering if there's a reason that I haven't located yet through searching?
I did find this StackOverflow question and answer HTTP Get: Only download the header? (HEAD is not supported) and while I agree with the statement, I don't want the overhead of requesting the headers and the body.
Any suggestions please?
Julie
Thank you to Kevin for suggesting that I use an error handler. I should've thought to try that myself, but I didn't.
Anyway, that lead me to the answer to my problem. To try and catch an error in $resource, it's suggested you use interceptors. I've never used them before and I utilized AngularJS documentation (https://docs.angularjs.org/api/ng/service/$http#interceptors) and changed the code in my factory to be:
myApp.factory('GetNumber', ['$resource',
function($resource) {
var get_headers = $resource('some/url', null, {
get_number: {
method: 'HEAD',
interceptor: { response: function(response) {
var count = response.headers()['x-number']:
return count ? count : 0;
}, responseError: function(rejection) {
console.log('rejection: ', rejection);
}}
}
});
return get_headers;
}
]);
I'm still not sure why transformResponse stopped working and I now need to use interceptor, but very happy I don't have to request the whole body now!
Julie

angular $http.post returns code 302

I have the following php:
public function getLoggedInUser()
{
if($this->isAjax())
{
exit (json_encode($_SESSION['User']));
}
}
And the following angular:
userModule.controller('UserController', [ '$http', function($http)
{
var userCtrl = this;
this.user = {};
$http.post('/User/getLoggedInUser', {request: 'ajax'}).success(function(data)
{
userCtrl.user = data;
});
}]);
i get code 302 but no result is found and the php script is not running.
What am i doing wrong?
Update
After debugging i the core of my PHP i can see that the variable request is not send to the server.
Why isnt it?
Note I’m no PHP expert, but I did some testing relating to one other AngularJS post request few days ago, which is quite similar to this one. So my solution here is based on my experience relating to that previous PHP post data experience. Also php manual for $_SESSION was used here.
First of all I’d put your php code in a getLoggedInUser.php file like below:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
echo $_SESSION["User"];
}
?>
and then make some changes to the
UserController
//added $scope in the controller's function parameters, just in case
userModule.controller('UserController', [ '$http', function($scope, $http)
{
var userCtrl = this;
this.user = {};
//let’s pass empty data object
var dataObj = {};
$http.post('User/getLoggedInUser.php', dataObj).
success(function (data, status, headers, config)
{
console.log("success");
userCtrl.user = data;
//if the above doesn’t work, try something like below
// $scope.userCtrl.user = data;
})
.error(function (data, status, headers, config)
{
console.log("error");
});
}]);
I hope this helps with the issue.
Some notes: AngularJS is quite new to me, and if someone has different view how this post call should be made, then feel free to comment on this solution :-) Btw, I looked on some other php post issue solutions (without AngularJS) like this one, and I’m still uncertain what’s the best way of handling this post issue.

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.

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