Resolving a python array wrapped in Json with Angular.js $resource - angularjs

I am working with webapp2 and Angular's $resource, I am having hard time finishing the job and resolving my data array from JSON format within my controller.
in my python handler, the array wrapper to JSON format is as follows:
self.response.write(json.encode(self.getVertices()))
and here is my service code in Angular:
angular.module('myPage').service('onServices',['$resource','$q',
function($resource,$q){
this.getMesh = function(){
var Mesh = $resource('/context/actors/one',
{}, {get: {method:'GET', isArray:true,responseType:'json'}})
return Mesh.get().$promise.then(function(data) {
one = data
return one})
}
}]);
and my controller code is this:
$scope.bck = onServices.getMesh();
when I log 'data' inside the service, it shows as series of 'resource' each of which containing a row of the array. And when I log the data inside the controller, it is still in 'promise' format, which contains the series of 'resource' (array rows). I can see the data inside the promise, but I am not seeing the data in the expected format, which is JSON. thanks.

Do you get JSON when you call the python part? Have you tried this Python JSON docs
self.response.headers['content-type'] = 'text/plain'
self.response.write(json.dumps(self.getVertices()))

Related

$resource URL data issue

From where the data is coming/posted in following code given in angular tutorial.I tried the same using json file but data is not getting posted or updated in json file .
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'#id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
The first parameter to $resource() is the url where the data is coming from (for GET) or posted (for POST). Parts of the url not supplied will default to the current page url, so for example if the page using this code is at http://example.com:8080/somepath/example.html then this resource would be getting data from http://example.com:8080/user/123/card/456 (or whatever #id is).

Unable to get data from RESTfull API using AngularJS and $resource

I'm making a mobile app using ionic (based on the AngularJS framework) where I want to display data from a RESTfull API. I'm pretty new to AngularJS so I'm not familiar with the best practices. I want to get data from this API but with a weeknumber parameters in the URL so I can get data from specific weeks. I have looked especially to the example of the AngularJS website.
This is what I have in my services:
var eventServices = angular.module('starter.services', ['ngResource']);
eventServices.factory('EventServiceAPI',['$resource',
function($resource) {
return $resource('http://localhost:8080/schedulingAPI/plannedevents?weeknumber=:weeknumber', {}, {
query: { method: 'GET', params:{weeknumber:'weeknumber'}, isArray: true}
});
}]);
This is what I have in my controller to get the API data:
$scope.events = EventServiceAPI.get({weeknumber: 7});
However, I still keep getting the error:
Error: [$resource:badcfg] object
When I use the full API URL in services and $scope.events = EventServiceAPI.query() in my controller, the full API-data is displayed without error.
I also don't get where to put the parameters; in the brackets after the resource URL or the params option in the query method.
Edit:
The output of http://localhost:8080/schedulingAPI/plannedevents?weeknumber=:weeknumber
[{"id":2985,"event":{"eventId":589,"subject":"Masterproef","year":2014,"weekNumber":7,"dayNumber":6,"startHour":8,"startMinute":10,"endHour":12,"endMinute":45,"startTime":"2014-02-14T07:10:00Z","endTime":"2014-02-14T11:45:00Z","classgroups":[{"id":8,"name":"4ELICTI"},{"id":4,"name":"4ENAU"},{"id":10,"name":"4ELICTE"},{"id":1,"name":"4CHB"},{"id":3,"name":"4ENEL"},{"id":9,"name":"4EMEM"},{"id":2,"name":"4CHC"},[]],"teacher":null},"rooms":[{"id":24,"abbr":"D015"}]},{"id":4021,"event":{"eventId":604,"subject":"Bedrijfsbeleid 2 hc","year":2014,"weekNumber":7,"dayNumber":6,"startHour":8,"startMinute":10,"endHour":9,"endMinute":35,"startTime":"2014-02-14T07:10:00Z","endTime":"2014-02-14T08:35:00Z","classgroups":[{"id":6,"name":"4ELICT"},[]],"teacher":null},"rooms":[{"id":44,"abbr":"G120"}]}]
Replace params:{weeknumber:'weeknumber'} with params:{weeknumber:'#weeknumber'}, notice the #.
If the parameter value is prefixed with # then the value of that
parameter is extracted from the data object (useful for non-GET
operations).
From angular documentation
And call your function with query:
$scope.events = EventServiceAPI.query({weeknumber: 7});
Actually, you can simplify your resource declaration like this:
eventServices.factory('EventServiceAPI',['$resource',
function($resource) {
return $resource('http://localhost:8080/schedulingAPI/plannedevents');
});
}]);
Angular will automatically append the query string for you

Angular factory with parameters

I have a small factory which requests data from a database (through php pages which return json objects). However to do this I need to set certain parameters in the get request. I have created a factory object to make the request.
app.factory('getplayerfactory', function($http){
return{
getPlayer: function(callback, name, currentinnings) {
var file = "/ajax.php?file=getplayer&displayname="+name+"&currentinnings="+currentinnings
$http.get(file).success(callback)
}
}
})// end of getplayersfactory
(I am using npm coding standard so no semi colons at the end of lines)
In my controller I want to call this factory and then use the results to fill data. I have tried to use the following to call this
getplayerfactory.getPlayer(function(results, "M. Millent", 1){
$scope.players[0].setHowout(results.howout)
})
However this creates an error when I introduce more parameters than results. I have used this factory pattern with other $http data request where the get request does not need parameters which works fine.
How do I make a get request which sets parameters? or do I need to create a separate factory for each set of parameters?
function(results, "M. Millent", 1) { is not a valid function signature
I think this is what you meant:
getplayerfactory.getPlayer(function(results){
$scope.players[0].setHowout(results.howout)
}, "M. Millent", 1)

How to populate Angular UI Bootstrap Typeahead with newest $resource

According to this Paweł Kozłowski's answer, Typeahead from AngularUI-Bootstrap should work when asynchronously obtaining popup items with $resource in newest Angular versions (I'm using 1.2.X).
Plunk - Paweł's version - Typeahead with $http
I guess I don't know how to use it properly (As a result I get an error in typeaheadHighlight directive's code - typeahead treats instantly returned Resources as strings and tires to highlight them).
Plunk - Typeahead with $resource
I think the critical code is:
$scope.cities = function(prefix) {
var p = dataProviderService.lookup({q: prefix}).$promise;
return p.then(function(response){
$log.info('Got it!');
return response.data;
});
return p;
};
I've tried bunch of stuff - returning $promise (version from Plunker), query(), then().
Currently, I'm using $http for this functionality in my app and I'm ok with it. Still, just wanted to know how to achieve the same with $resource.
You might want to take a look at this: https://github.com/angular/angular.js/commit/05772e15fbecfdc63d4977e2e8839d8b95d6a92d
is ui.bootstrap.typeahead compatible with those changes in $resource's promise API ?
Should be:
$scope.cities = function(prefix) {
return dataProviderService.lookup({q: prefix}).$promise.then(
function(response){
// might want to store them somewhere to process after selection..
// $scope.cities = response.data;
return response.data;
});
};
This is based of the angular commit mentioned above, and it worked for me on Angular 1.2.13
Thanks to the answer from #andrew-lank, I did mine with $resource as well. I didn't have a data attribute in my response though. I used the query method on $resource, which expects a responsetype of array so maybe that is why there is no data attribute. It is an array of Resource objects, each of which contains the data. So my code is slightly simpler, looks more like this:
$scope.cities = function(prefix) {
return dataProviderService.query({q: prefix}).$promise.then(
function(response){
return response;
});
};
I ran into this same problem and it had me banging my head against the wall. The problem is with the data service since it is returning an array of strings instead of wrapping them in a JSON object. $resource will not work with an array of strings.
For additional info, check out this answer:
One dimensional array of strings being parsed to 2d by angular resource
typeahead="i.t_UserName for i in employeeInfo | filter:$viewValue | limitTo:4"
goes as an attribute of your html input
and in your controller (using employee resource)
$scope.employeeInfo = getEmployeeResourceSvc.getEmplInfo.query(function(response){
$scope.employeeInfo= response;
});
In the ui-bootstrap 13.0 and angular 1.3, you can now do the following:
$scope.cities = function (q) {
return $scope.resource.query({ q: prefix }).$promise
}

Angular $httpProvider transformResponse data contains local HTML DOM elements?

When I instantiate the following code in an AngularJS app, I get weird data in the transformResponse function (bottom of code). I'm not calling the $resource function from any controller, just loading the script in a browser. The data variable (see code) contains the HTML of the current partial, when loading the app.
This seems odd. Is this the way it's supposed to be?
var buddyServices = angular
.module('buddyServices', ['ng','ngResource'])
.factory('Buddy',
function ($resource) { console.log('resource');
return $resource('http://webservice.buddyplatform.com/v1/:service',
{service:'', BuddyApplicationName: 'xxx',
BuddyApplicationPassword: 'yyy'}
);
}
)
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.transformResponse = function(data) {
console.log(data);
return 'TEST: '+data;
};
});
=== EDIT ===
It just daunted on me: $httpProvider handles all http requests, so a page load is one of those. I'm guessing a bit now, but it seems probable. So, the question then becomes: Is there an "easy" way to constrain the data in the code above to only those requests performed by my service?
transformResponse takes another parameter headersGetter. You can use this to get the headers send with the response. Look for Content-Type header header. It should contain application/json

Resources