Angular- Couldnot parse json response in front-end - json

I made an httpRequest fetch some items using following code:
factory.getBanners = function() {
$http({
method: 'GET',
url: 'http://localhost:2100/v1/items/getBanners'
}).then(function successCallback(response) {
console.log(response);
return response;
});
};
In controller I handled it as following:
store.controller('bannerCtrl', ['$scope', 'productService', function($scope, productService){
$scope.init = function() {
$scope.banners = productService.getBanners();
}
$scope.init();
}]);
In front end I tried to display data using
<div ng-controller="bannerCtrl">
<div data-ng-repeat="banner in banners">
<li> {{banner.bannerAltText}} </li>
</div>
</div>
But it doesn't display anything. Neither it gives any error on console. How can I resolve this issue. Here banners is an array whose each element contains bannerAltText.

Your getBanners-function does not work the way you think it does. It returns nothing. The return statement in the then function only returns from that then-function, not from getBanners. The problem is that you are trying to use an asynchonous function in a synchronous way. Instead make getBanners return a promise:
factory.getBanners = function() {
return $http({
method: 'GET',
url: 'http://localhost:2100/v1/items/getBanners'
}).then(function successCallback(response) {
return response.data;
});
};
And use that promise in your controller:
$scope.init = function() {
productService.getBanners().then(function(banners) {
$scope.banners = banners;
});
}
$scope.init();

A return in a in .then() will be a promise, rather than the data. here is a better way to construct your code
factory.getBanners = function() {
return $http({
method: 'GET',
url: 'http://localhost:2100/v1/items/getBanners'
});
};
.
store.controller('bannerCtrl', ['$scope', 'productService', function($scope, productService){
$scope.init = function() {
productService.getBanners()
.then(function(response) {$scope.banners = response.data});
}
$scope.init();
}]);

Related

Unknown provider: callbackProvider <- callback

I am stuck with this code for very long time and apply all the patches available on net but didn't find the effective one.It is still giving error while calling service from controller.
Here the code below
<HTML ng-app="myApp">
<body ng-controller = "myCtrl">
<div>{{me}}</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script>
var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope,myService){
myService.getx(function(data){
console.log(data);
$scope.me = "data";
});
});
</script>
<script>
app.service('myService',function($http,callback){
this.getx= function(){
return $http({
method: "GET",
url: "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
}).then(function (response) {
console.log(response)
return callback(response);
}, function (error) {
throw error;
console.log("Error",error)
});
}
});
</script>
</HTML>
i'd rewrite it like this:
APP CTRL:
var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope,myService){
myService.getx()
.then(
function(data){ //handle the $http promise here
console.log(data);
$scope.me = "data";
},
function(err){
console.log('error:' + err);
});
});
SERVICE:
app.service('myService',function($http){
return {
getx: function() {
return $http({ //the $http returns a promise
method: "GET",
url:"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
});
}
}
});

how to define angular methods

I'm a regular consumer of advice from Stackoverflow. It's an invaluable tool - thanks for all the help!
But this is my first question: I'm very new to Angular but I've been doing server side stuff for donkeys years.
I've got a method on a controller, which calls a server REST service. My problem is that the method is called whenever the controller is instantiated. I know there's got to be another way of declaring the function, but I've got no idea of what to search for.
Here's my html:
<html lang="en" data-ng-app="mLS" ng-controller="mLSController">
<head>....</head>
...
<li><a ng-if="userName" ng-click="Logout()">logout</a></li>
and my module (the module def is elsewhere, but it seems ok)
var app = angular.module('mLS');
app.controller('mLSController', function ($scope, $http, $window, $location) {
$http({
url: '/api/UI/GetUsername',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
//app.
// controller('mLSController', function ($scope, $http) {
// $scope.Logout = function () {
// $http({ url: 'api/UI/Logout', method: 'GET' });
// };
// });
//app.
// controller('mLSController', ['$scope', '$http', 'Logout', function ($scope, $http, Logout) {
// $scope.callLogout = function () {
// Logout();
// };
// }]).
// factory('Logout', ['$http', function (protocol) {
// protocol({ url: 'api/UI/Logout', method: 'GET' }).success(function() {
// $scope.Logout = true; });
// }]);
So my problem is that the current code:
function Logout($http) {
$http({ url: '/api/UI/Logout', method: 'GET' });
}
just isn't called at all, and if I put it on the controller, Logout() is called when the controller is instantiated. Which isn't ideal.
Please help!
If you want the Logout function to be exposed to DOM (via Angular), you need to put it on $scope. There is no other option to call it using angular directives (ng-click).
Else, if you want it to be called before your app/controller are instantiated, use native javascript's onclick() event.
Warning: if you use onclick, you cannot set $scope variables.
So, thanks to Bharat, I've got it working!
This is the solution:
var app = angular.module('mLS');
app.controller('mLSController',
// function added to the controller
function ($scope, $http, $window, $location) {
$scope.Logout = function () {
$http({ url: 'api/UI/Logout', method: 'GET' });
return ;
};
$http({ url: '/api/UI/GetUsername', method: 'GET' }).success(function (data, status, headers, config) {
$scope.userName = data;
$scope.desiredPath = $location.path();
if (!$scope.userName && $scope.desiredPath != '/Account/Login')
$window.location.href = '/Account/Login';
});
});
For completeness, I could wrap the GetUsername call in a function, but the question is answered.
I can't upvote your answer, Bharat, because I haven't asked enough questions yet, but thanks so much!

How to call jsonp api using $http in angularjs

// this is service where i m calling api
app.factory('users',['$http','$q', function($http , $q) {
return {
getUsers: function() {
var deferred = $q.defer();
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK';
$http.jsonp(url).success(function (data, status, headers, config) {
console.log(data);
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
//this always gets called
console.log(status);
deferred.reject(status);
});
return deferred.promise;
}
}
}]);
//this is my controller where i calling getUsers();
app.controller('myCtrl', function($scope, users) {
$scope.data = users.getUsers();
})
while calling it gives me error
Uncaught ReferenceError: callback is not defined(anonymous function)
Plz give me proper solution so that i can see me api data in <div>. Thanks in advance
$http already returns a promise. There is no need to form a promise of a promise. Try this:
app.factory('Users', ["$http", function($http){
return {
getUsers: function(url) {
return $http({
url: url,
method: 'JSONP'
});
}
};
}]);
Controller:
app.controller("MyCtrl", ["$scope", "Users", function($scope, Users) {
$scope.data = [];
Users.getUsers('http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK').then(function(response){
console.log(response.data);
$scope.data = response.data;
}).catch(function(response){
console.log(response.statusText);
});
}]);
Here the scenario is a bit different as you have to declare a $window.callback function.
Code
var app = angular.module("demoApp", []);
app.factory('UserService', ['$http', function ($http, $q) {
var getUsers = function () {
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=callback';
return $http.jsonp(url);
};
return {
GetUsers: getUsers
}
}]);
app.controller("demoController",
["$scope", "$window", "UserService",
function ($scope, $window, UserService){
UserService.GetUsers();
$window.callback = function (response) {
$scope.countries = response.Results;
}
}]);
Plunkr: http://plnkr.co/edit/MFVpj1sMqJpcDg3ZwQFb?p=preview

retrieve json data using GET in angularjs

I've got some data stored in a nosql database that I'm able to see in when accessing localhost:3000/countries.
I'm trying to use this factory in order to get the data which is in json.
.factory('countries', ['$http', '$q',
function($http, $q) {
var countries = {
get: function() {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: '/countries'
}).then(function(response) {
resolve(response.data);
}, function(error) {
reject(error);
});
});
};
return countries;
}
]);
And then I'm attempting to use this controller to send that data to the appropriate url to be displayed but it isn't working as I expected it to.
.controller('CountriesCtrl', function($scope, countries) {
console.log(countries);
countries.get(function(countries) {
$scope.countries = countries;
});
})
Any thoughts or suggestions? Thanks!
This is what I use currently in my project that uses Mongodb
cmsApp.factory("tasks", ["$resource", function($resource) {
return $resource("/tasks/", {}, {
save: {
method: 'POST',
isArray: true
},
'delete': {
method: 'DELETE',
isArray: true
}
});
}]);
Then in the Controller(make sure to inject it to controller!):
$scope.tasks = tasks.query();
.query() selects all of the data while .get() gets on by Id
You should inject your factory into your controller, something like this:
.controller('CountriesCtrl', function($scope, devices) {
console.log(countries);
countries.get(function(data) {
$scope.data = data;
});
})
You should inject service 'devices' instead of it's internal variable 'countries'.
.controller('CountriesCtrl', function($scope, devices) {
console.log(devices);
devices.get().then(function(countries) {
$scope.countries = countries;
});
});

angularJS add JSON by http request

want to download a JSON of beercat('bieres.json') in this.bieres
How could I do?
function() {
var app = angular.module('monStore', []);
app.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'bieres.json'
});
}
});
app.controller('StoreController', function($scope,dataService){
this.bieres = [];
dataService.getData().then(function(dataResponse) {
$scope.bieres = dataResponse.data;
});
...
});
I think it's my access by this.bieres that it's wrong,
the Json is loaded in the console, but a blank page is in result