AngularJS HTTP Call / Response - javascript

This is probably something very simple but I am having some problem making an HTTP GET request, getting the data back, and attaching it onto the javascript global window variable.
Simple HTTP Call:
$http.get("production/dashboard?dashboard_type=A").success((data) ->
$scope.pods = data;
window.pods = $scope.pods.to_json;
window.type = 'A';
alert(window.pods)
alert(window.type)
alert "success1"
return
).error (data, status, headers, config) ->
return
Upon execution, I am getting:
1. Alert("undefined")
2. Alert("A")
I thought that the promise of the http request will get resolved when the response returns?
I checked the Network tab and there is indeed JSON data being sent back as the response to the request.
I must be missing something simple...

$http.get("production/dashboard?dashboard_type=A")
.success(function(data) {
$scope.pods = data;
window.pods = $scope.pods;
window.type = 'A';
alert(window.pods);
alert(window.type);
alert("success1");
return
}).error (function(data, status, headers, config){
return;
});
This is assuming it has access to the window where your code is. Is this wrapped in a module and controller?

As we need json data to get from $http.. Trying putting .json like below.
$http.get('/products.json')
Regarding your another issue.. you might get a hint with this link AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Related

Get tweets using angularjs

I am trying to make an app with material design and angularjs to get the tweets using hashtag search.
getTweets: function(hashtag, since,$http) {
var cfg = {};
var paramSince = since ? '&since_id='+ since : '';
var queryUrl = 'https://api.twitter.com/1.1/search/tweets.json?q=%23'+hashtag+paramSince;
// var queryUrl = '/search?hashtag='+hashtag+paramSince;
var promise = $http.get(queryUrl, cfg).then(function (response) {
return response;
});
return promise;
}
This API returns error 215, Bad Authentication Data
Here is the full application
STEPS TO REPRODUCE:
(i) Click Add Account
(ii)Login
(iii) Click finish
$http is undefined. You injected $http service into your twitterApp.services factory, then you (try) redeclared it inside the returned function getTweets.
In this case there is no "magic", you call getTweets with two arguments, so $http becomes undefined. The solution is removing this parameter from getTweets and use $http as a closure.
UPDATE:
There's no error handling in the process, you have to reject the promise when error occurs. This way you can also see the error comes from the server.
http://plnkr.co/edit/Lbb6EvwsjuecmFn5Vchd?p=preview
As you can see on the console, when trying to get connected, the server returns an origin error:
Error: Origin "http://run.plnkr.co/Of0F9UHpjhrqkjdw/" does not match
any registered domain/url on oauth.io(…)
It's probably about settings in your server (in this case, oauth.io) in terms of CORS.

Angular HTTP within a HTTP Interceptor

I need to append the necessary HMAC headers to a request. This should not be very difficult however I am starting to get frustrated. What is wrong with the following code. The actual http call I am doing works; I have run this call myself and it returns the necessary data. It does not work inside the interceptor.
I merely want to get the current implementation working before I add whitelist or blacklist and other customizable data for this interceptor. This is not a question about hmac however but with promises.
The error in this interceptor is with the entire promise line starting at $http(...). When i remove this block and use it as is (minus promise execution) it works fine. As soon as i uncomment the line it gets stuck in a loop and crashes chrome. Everywhere I have read says this is how it is done, but this clearly does not work.
function requestInterceptor(config){
var $http = $injector.get('$http');
var deferred = $q.defer();
$http.get(hmacApiEndpoint, {cache: true}).then(function(data){
console.log('HMAC - Success', data)
deferred.resolve(config)
}, function(config){
console.log('HMAC - Error', config)
deferred.resolve(config)
})
return deferred.promise;
}
return {
request: requestInterceptor
};
Does this have something to do with the fact that angulars $http promise is a different implementation than that of '$q'?
It doesn't look like you are actually amending the config with the newly obtainted HMAC.
Also, you'd need to protect against your requestInterceptor intercepting the call to obtain the HMAC, thus resulting in an infinite loop.
And lastly, you don't need deferred here - just return the promise produced by $http (or $http.then()):
function requestInterceptor(config){
var $http = $injector.get('$http');
// just return, if this is a call to get HMAC
if (config.url === hmacApiEndpoint) return config;
return $http.get(hmacApiEndpoint, {cache: true})
.then(function(response){
console.log('HMAC - Success', response.data)
// not sure where the HMAC needs to go
config.headers.Authorization = response.data;
return config;
})
.catch(function(){
return $q.reject("failed to obtain HMAC");
});
}
return {
request: requestInterceptor
};

Posting data to JSON - Angular .post

I am working on an application and am having an issue posting to a .JSON file in my assets. I am working with an Angular based application. The error code I get is 404 with a response of: Cannot POST /assets/data/card-stack.json. Now the problem is, when I work with my get to retreive the JSON data it works perfect. It is only when I am using .post. Here is what I am doing:
$http.get('./../../assets/data/card-stack.json').success(function(data) {
$scope.cards = data;
// Set the showdown images from the card data grabbed from the card-stack.json file
$scope.showdowns = [
$scope.cards[0].url,
$scope.cards[1].url,
$scope.cards[2].url,
$scope.cards[3].url
];
});
// Simple POST request example (passing data) :
$http.post('./../../assets/data/card-stack.json', {url : './../images/banana.jpg'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
console.log(data);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Suggestions?
A .json file is a static file that just contains json data so you won't be able to post to it. Instead you would need to use a server side page or service such as php to process the posted data.
Try to set the $http header:
$http.defaults.headers.post["Content-Type"] = "application/json";
Try it.

POST Ajax request by AngularJS to Symfony controller

I'm trying to do an Ajax request from my angularJs controller to my Symfony controller. However, for an unknown reason, I cannot receive the data in my Symfony controller. My controller gets called and I can return some information that I will see in the success function on the AngularJS side. However, the data I'm sending via AngularJs cannot be retrieved on the Symfony controller.
Here's what I'm doing on the AngularJS side:
$http.post('{{ path('admin_ima_processmanagement_project_save', {'id':object.id}) }}',{"projectJson":"test"}).
success(function(data, status, headers, config) {
console.log("yeah");
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("oh non");
console.log(data);
});
I can see in my console "yeah" that is appearing after the execution of this request.
In my Symfony controller, I have the following:
$request = $this->container->get('request');
$projectJson = $request->query->get('projectJson');
$response = array("code" => 100, "success" => true, "projectJson" => $projectJson);
return new Response(json_encode($response));
On the console, after the call, I get {"code":100,"success":true,"projectJson":{}} meaning that projectJson is unfortunately empty...
What should I do to retrieve the data that I'm sending from my client ?&
In class Request property query refers to GET parameters.
In your case you need to access to POST parameters, which are in request property.
So your code should look like this:
$projectJson = $request->request->get('projectJson');
More info about Request you will find here.
Symfony2 does not support AngularJS $http data. Because AngularJS sends data as request body, and SF2 reads only $_GET and $_POST.
You have 2 solutions:
Update Php code to handle such data
Update JS code to send classic form data (check https://gist.github.com/bennadel/11212050 for this)

Angular $http error callback response is always undefined

I am having issues trying to gracefully handle $http errors. I am looping over a list of servers to make API calls to for status. The calls that complete successfully for perfectly. The ones that fail are not giving me access to the error information. It is always undefined. Here is the code snippet:
angular.forEach($scope.servers, function (server) {
// blank out results first
server.statusResults = {};
$http.jsonp(server.url + '/api/system/status?callback=JSON_CALLBACK', {headers: { 'APP-API-Key': server.apiKey }}).
success(function (data, status, headers, config) {
server.statusResults = data;
}).
error(function (data, status, headers, config) {
// data is always undefined here when there is an error
console.error('Error fetching feed:', data);
});
}
);
The console output shows the correct 401 error (which I didn't output) and my console error message (which I did output) with an undefined data object.
GET https://server_address/api/system/status?callback=angular.callbacks._1 401 (Unauthorized) angular.min.js:104
Error fetching feed: undefined
What I am trying to do is NOT have Angular display the 401 in the log, and instead I will display it in a graceful way. However since data is undefined I have no way of accessing the information.
I am new to AngularJS, but my example closely matches other examples I've found in the documentation.
I've also tried using $resource instead of the $http and got the exact same problem.
var statusResource = $resource(server.url + '/api/system/status', {alt: 'json', callback: 'JSON_CALLBACK'},
{ status: {method: 'JSONP'}, isArray: false, headers: { 'APP-API-Key': server.apiKey } });
// make status API call
statusResource.status({}, function (data) {
server.statusResults = data;
}, function (err) {
// data is always undefined here when there is an error
console.log(err);
});
I'm probably doing something obviously wrong, but I'm not sure what else to try.
Per the $http docs, body is
The response body transformed with the transform functions.
With the 401 (Unauthorized) error you are getting back, it is quite possible there is no body being returned, hence why it is undefined.
If you want to log the error code, log the status parameter instead. It contains the HTTP Status Code, which should be uniform, unlike response bodies.

Categories