Not able to get angular to read in an object fetched via service. Error message in brower is really vauge, doesn't reference any of my code lines. I checked via Chrome Developer tools and the api call is getting made. Any ideas?
Error message:
TypeError: undefined is not a function
at copy (http://127.0.0.1:5000/static/lib/angular/angular.js:593:21)
at http://127.0.0.1:5000/static/lib/angular/angular-resource.js:410:19
at wrappedCallback (http://127.0.0.1:5000/static/lib/angular/angular.js:6846:59)
at http://127.0.0.1:5000/static/lib/angular/angular.js:6883:26
at Object.Scope.$eval (http://127.0.0.1:5000/static/lib/angular/angular.js:8057:28)
at Object.Scope.$digest (http://127.0.0.1:5000/static/lib/angular/angular.js:7922:25)
at Object.Scope.$apply (http://127.0.0.1:5000/static/lib/angular/angular.js:8143:24)
at done (http://127.0.0.1:5000/static/lib/angular/angular.js:9170:20)
at completeRequest (http://127.0.0.1:5000/static/lib/angular/angular.js:9333:7)
at XMLHttpRequest.xhr.onreadystatechange (http://127.0.0.1:5000/static/lib/angular/angular.js:9303:11)
Service:
angular.module('angularFlaskServices', ['ngResource'])
.factory('Pic', function($resource) {
return $resource('/api/pic/:picId', {}, {
query: {
method: 'GET',
params: { picId: '' },
isArray: true
}
});
})
;
Angular Controller:
function ProfileController($scope, Pic) {
var picsQuery = Pic.get(function(pics) {
$scope.pics = pics;
});
}
Flask View:
#app.route('/api/pic/')
def on_recent():
if not session.has_key('access_token'):
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=session['access_token'])
recent_media, next = api.user_recent_media()
print recent_media
photos = []
for media in recent_media:
if (media.type != "video"):
photos.append({"picId": 1, "url": media.get_low_resolution_url()})
except Exception as e:
print(e)
return json.dumps(photos)
Your service code looks good but I am not sure if you have all of your dependencies injected properly.
var app = angular.module('myApp', ['angularFlaskServices']);
app.controller('ProfileController', [
'$scope',
'Pic',
function($scope, Pic) {
var picsQuery = Pic.get(function(pics) {
$scope.pics = pics;
});
}]);
Related
I'm a new developer and I'm having some issues. I'm using AngularJS and I use a service to return the users from a database.
I have an factory in my Service.js to specify the http service:
dashboard.factory('User', ['$resource', 'urlPrefix',
function ($resource, urlPrefix) {
return $resource(urlPrefix + '/user/json/getUsersByName', {
id: '#id'
}, {
getUsersByName: {
globalError: false,
method: 'GET',
isArray: true
}
});
}
]);
The user controller receives two entries(userName and maxResults):
#ControllerSupport
public List< User > getUsersByName() {
String userName = getParameter( "userName", String.class );
Integer maxResults = getParameter( "maxResults", Integer.class );
return userService.findByName( userName, maxResults );
}
I'm calling the service as you can see above:
$scope.queryDashboardUsers = function () {
User.getUsersByName({
'userName': $scope.username.search,
'maxResults': 100
}).$promise.then(
function (response) {
console.log('users', response);
});
};
And receiving the following error:
Error: **[$resource:badcfg] ** object http://errors.angularjs.org/1.2.20/$resource/badcfg?p0=array
As I was reading in the forum, query returns an array and get returns an object.
So I've tried to call:
return $resource(urlPrefix + '/user/json/getUsersByName', ...).query();
and
return $resource(urlPrefix + '/user/json/getUsersByName', ...).get();
And neither them worked.
If I look at "Network" in Chrome, I can see the request response and that's right. So I imagine that I'm having a problem of conversion between Object and Array but I have no idea where.
Could someone help me?
I solved the problem changing the service to:
dashboard.factory('User', ['$resource', 'urlPrefix',
function ($resource, urlPrefix) {
return $resource(urlPrefix + '/user/json/getUsersByName', {}, {});
}
]);
But I really don't understand why the service before didn't work. Does someone know?
i have problem with ngResource.
here is my .factory
app.factory('sveKlupeServiceFactory', ['$resource',
function($resource){
return $resource('myURL/to/json', {},{
// { method: 'getKlupe', q: '*' },
query: { method: 'GET', params:{klupaId:'klupe'}, isArray:true}
});
and here is my controller
app.controller('klupeController', ['$scope', 'sveKlupeServiceFactory', function ($scope,sveKlupeServiceFactory){
$scope.klupe = sveKlupeServiceFactory.query();
}]);
and in html I have this
<tr ng-repeat="klupa in klupe">
<td>{{klupa.serial_number}}</td>
<td>{{klupa.location_id}}</td>
<td>{{klupa.type}}</td>
<td>{{klupa.last_report_dt}}</td></tr>
Problem:
in my browser I have table, but with empty row. There is no any error.
In my app I have
var app = angular.module('App', [
'ngRoute',
'ngResource']);
Can someone help me with any suggestion?
Thank you.
If you want entire table data, then there is no need to pass id as parameters in factory.Make the following changes in controller while calling factory method.
Check the response using console.log()
sveKlupeServiceFactory.query(function(res){
console.log(res);
$scope.klupe = res;
});
You should use promises to get the response.
$scope.klupe = sveKlupeServiceFactory.query();
$scope.klupe.$promise.then( function(result) { $scope.klupe = result });
I m trying to connect my angular front end with Jenkins API.
my service.js
angular.module('jenkinsLightApp')
.factory('JenkinsService', function (CONFIG, $location, $http, $httpBackend) {
return {
getJobs: function () {
var viewParameter = 'All';
if ($location.search().view) {
// Set the value of the view query parameter
viewParameter = $location.search().view;
}
// Call Jenkins API
var promise = $http({method: 'GET', url: 'http://xx.xx.xxx.xxx:xxxx/pic/view/All/api/json'}).
then(function successCallback(response) {
alert('promise');
// Initialize jobs data
var data = response.data;
var jobs = [];
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
};
I have removed the authentication from jenkins, so angular can be able to connect.
But I have the following error:
Error: Unexpected request: GET http://xx.xx.xxx.xxx:xxxx/pic/view/All/api/json
No more request expected
$httpBackend#http://localhost:9000/bower_components/angular-mocks/angular- mocks.js:1180:1
sendReq#http://localhost:9000/bower_components/angular/angular.js:8442:1 http/serverRequest#(http://localhost:9000/bower_components/angular/angular.js:8162:16qFactory/defer/deferred.promise.then/wrappedCallbackhttp://localhost:9000/bower_components/angular/angular.js:11722:3
I have also tried to add
$httpBackend.whenGET(/pic/).passThrough();
that removed the error but I m still unable to dislplay any jenkins job in the browser.
Thanks for your help
I have an AngularJS app. In this app, I'm trying to ping a REST API. This API returns a list of orders.
I need to be able to handle the scenario where I successfully GET the orders. I also need to handle the
scenario where the request to GET the orders fails. In an attempt to do this, I'm using the ngResource
module. My controller looks like the following:
myController.js
myApp.controller('myController',
function myController($scope, myService) {
myService.getOrders(function(data) {
$scope.orders = data;
});
}
);
The definition of myService is stored in myService.js. That file looks like this:
app.factory("myyService", function($resource, $log) {
return {
getOrders: function(onSuccess) {
var orders = $resource("http://localhost:1000/orders", { fetch:{method:'JSON'} });
orders.fetch(function (response) {
console.log(response);
onSuccess(response.data);
});
}
};
});
When I run this code, I get a runtime error. The error says:
TypeError: Object function g(b){z(b||{},this)} has no method 'fetch'
Maybe there has to be something I don't understand. In my mind, I see fetch defined.
The other question I have is how do I set this up to handle failed requests? Like a 404 or 502?
You forgot the curly braces after the URL parameter...
Change: http://localhost:1000/orders", { fetch :
To: http://localhost:1000/orders", {}, { fetch :
app.factory("myyService", function($resource, $log) {
return {
getOrders: function(onSuccess) {
var orders = $resource("http://localhost:1000/orders", {}, { fetch : {method:'JSON'} });
orders.fetch(function (response) {
console.log(response);
onSuccess(response.data);
});
}
};
});
[EDIT]
To handle errors from the server side, you need to set the second function in the resource call.
Example :
orders.fetch(function success() {...},
function error() {... this will execute in a http error, 400 or 500}
);
I'm trying to pick up angular.js and working on figuring out some of the things that are a bit less documented.
Consider this - I have a search method on the server that accepts query params and returns a collection of search results, and responds to GET /search.json route (Rails FWIW).
So with jQuery, a sample query would look like this:
$.getJSON('/search', { q: "javascript", limit: 10 }, function(resp) {
// resp is an array of objects: [ { ... }, { ... }, ... ]
});
I'm trying implement this using angular, and wrap my head around how it works. This is what I have now:
var app = angular.module('searchApp', ['ngResource']);
app.controller('SearchController', ['$scope', '$resource', function($scope, $resource){
$scope.search = function() {
var Search = $resource('/search.json');
Search.query({ q: "javascript", limit: 10 }, function(resp){
// I expected resp be the same as before, i.e
// an array of Resource objects: [ { ... }, { ... }, ... ]
});
}
}]);
And in the view:
<body ng-app="searchApp">
...
<div ng-controller="SearchController">
...
<form ng-submit="search()">...</form>
...
</div>
</body>
However, I keep getting errors like TypeError: Object #<Resource> has no method 'push' and $apply already in progress.
Things seem to work out as expected if I change the $resource initialization to the following:
var Search = $resource("/search.json?" + $.param({ q: "javascript", limit: 10 }));
Search.query(function(resp){ ... });
It seems more intuitive to initialize the $resource once and then pass different query parameters with changes in the requested search. I wonder if I'm doing it wrong (most likely) or just misunderstood the docs that calling $resource.query with the query params object as the first argument is feasible. thanks.
TypeError: Object # has no method 'push' and $apply already
in progress
because you have not defined a resources with the name Search. First you need to define such a resource. Doc: $resource. Here is an example implementation
angular.module('MyService', ['ngResource'])
.factory('MyResource', ['$resource', function($resource){
var MyResource = $resource('/api/:action/:query',{
query:'#query'
}, {
search: {
method: 'GET',
params: {
action: "search",
query: '#query'
}
}
});
return MyResource;
}]);
Include this module in you app and use it in a controller like this
$scope.search_results = MyResource.search({
query: 'foobar'
}, function(result){});
However I am not sure if this is what you need. The resource service interacts with RESTful server-side data sources aka REST API.
Maybe you need just a simple http get:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
http://docs.angularjs.org/api/ng.$http