SyntaxError: Unexpected token in $http.get() request - angularjs

I tried to make my first Angular app, but faced this error
JS code:
var app = angular.module('sortApp', [])
app.controller('sortController', ['$http', function ($http) {
var sort = this;
sort.orders = [];
$http.get('angular/orders.json').success(function (data) {
sort.orders = data;
});
Error log:
SyntaxError: Unexpected token n in JSON at position 17
at JSON.parse (<anonymous>)
at cc (angular.js:1139)
at Ud.e.defaults.transformResponse (angular.js:7481)
at angular.js:7429
at r (angular.js:325)
at xc (angular.js:7428)
at b (angular.js:8122)
at L (angular.js:11561)
at angular.js:11647
at k.$eval (angular.js:12673)
what could cause it?

your json is invalid format. Check it first.

Related

Angular js $resource error when calling query on $resource with path parameter

I am trying to hit an ajax call using $resource of angular js to get an array of objects.I am passing an path variable which is an id for the object and when i try to call query on $resource , it shows error given below.resource and controller code is given below.
i am using Spring MVC on backend, for rest controller of spring code is given below.Please give some suggestions, what i am doing wrong here and what is the best practice?
this is the error in console -
TypeError: V is not a function
at https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js:13:165
at n (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:7:427)
at C.setUrlParams (https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js:13:50)
at Function.l.(anonymous function) [as query] (https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.1/angular-resource.min.js:10:156)
at Object.getSubCategoryIdNameFn [as getSubCategoryIdName] (http://localhost:8080/MyCoupon/resources/js/category/category_service.js:17:71)
at r.$scope.catChanged (http://localhost:8080/MyCoupon/resources/js/coupon/coupon_controller.js:13:19)
at fn (eval at compile (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:213:110), <anonymous>:4:221)
at r.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:133:313)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:252:529
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:264:447
and here are my service and controller code -
function getSubCategoryIdNameFn(catId){
var deferred = $q.defer();
$resource("admin/rest/subcategory-id-name/:catId",{catId:"#catId"}).query({catId:catId})
.$promise
.then(function(response){
deferred.resolve(response);
},function(error){
deferred.reject(error);
});
return deferred.promise;
}
controller -
$scope.catChanged = function (){
categoryService.getSubCategoryIdName($scope.coupon.category).then(function(response){
$scope.subcatList = response;
},function(error){
});
}
i am new to angular, so have no idea what the console error saying?
server side controller is in spring -
#RequestMapping(value="subcategory-id-name/{catId}", method=RequestMethod.GET,produces={"application/json"})
public List<SubCategory> getSubCategoryIdAndName(#PathVariable int catId){
return subCategoryService.getSubCategoryIdName(catId);
}

AngularJS $http error No more request expected

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

Testing AngularJS resource with Jasmine

I would like to test my resource with following URL:
$resource(API_URL+'items/:id', {});
Where API_URL equals /app/api/
describe('item',function(){
it('should return same item id',function(){
$httpBackend.expectGET(API_URL+'items/1').respond({id:1});
var result = ItemService.item.get({id:1});
$httpBackend.flush();
expect(result.id).toEqual(1);
});
});
But the problem is that this test fails for some strange reason:
Error: Unexpected request: GET modules/home/partials/home.html
No more request expected
at $httpBackend
And when I add slash to $httpBackend URL like this:
$httpBackend.expectGET(API_URL+'/items/1').respond({id:1});
It throws following expection:
Error: Unexpected request: GET /app/api/items/1
Expected GET /app/api//items/1
at $httpBackend
Note double slash in expected GET.
How to fix it?
Update:
Code from ItemService:
var itemService = angular.module("ItemServiceModule", []);
itemService.factory("ItemService", [ "$resource", "API_URL", function($resource,API_URL) {
var itemService = {
item: $resource(API_URL+'items/:id', {})
};
return itemService;
}]);
Update2:
If I change httpBackend url like this (just add localhost and not adding slash before items):
$httpBackend.expectGET('http://localhost:8080'+API_URL+'items/1').respond({id:1});
Then the error is:
Error: Unexpected request: GET /app/api/items/1
Expected GET http://localhost:8080/app/api/items/1
at $httpBackend
Update3:
If I for example hard code that API_URL like this:
var url = 'app/api/items/1';
$httpBackend.expectGET(url).respond({id:1});
The error is:
Error: Unexpected request: GET /app/api/items/1
Expected GET app/api/items/1
at $httpBackend
But when I add slash at the begining of url, then it requests home partial modules/home/partials/home.html as with API_URL.
Error: Unexpected request: GET modules/home/partials/home.html
No more request expected
at $httpBackend
It turned out that the problem was with ui-router. Namely, the following configuration:
$urlRouterProvider.otherwise("/");
I just needed to eliminate this configuration in the tests:
beforeEach(module(function ($urlRouterProvider) {
$urlRouterProvider.otherwise(function(){return false;});
}));
Found this solution on https://github.com/angular-ui/ui-router/issues/212

trouble with angular and flask - error message vauge

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;
});
}]);

Error with DNN module

I have a comments module in my DNN site. I have installed that module on my site successfully but I am not able to work with it. It shows these errors.
Uncaught ReferenceError: ko is not defined
Uncaught TypeError: Cannot call method 'fromJS' of undefined
GEThttp://localhost:1726/resources/shared/scripts/jquery/jquery.min.map 404 (Not Found)
GET http://localhost:1726/jquery.min.map 404 (Not Found)
But I have defined ko in my JavaScript code:
function Comment(data) {
var self = this;
self.CommentId = ko.observable();
self.CommentText = ko.observable();
self.ModuleId = ko.observable();
self.PortalId = ko.observable();
self.updateFromJS = function (data) {
if (data != null && data != undefined)
ko.mapping.fromJS(data, {}, this);
};
self.updateFromJS(data);
};

Resources