angularJS add JSON by http request - json

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

Related

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};

Angular- Couldnot parse json response in front-end

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

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

AngularJS: read response data from server

I have a problem which should be wasy to solve, but I just cant figure out what I am doing wrong. I receive data through an $http request.
alert(data)
gives me object object
alert(data.response)
gives me {"id":"123456","post_id":"12345"}
alert (data.response.id)
gives me undefined
My question: I want to get the ID. Why does the last expression give me undefined and not the ID? Do I have to transform the data in some way?
I am thankful for any hints!
It looks like your data.response is a string.
You use angular.fromJson to convert it to object ie :
$scope.temp = angular.fromJson($scope.data.response);
please see working demo below
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope){
$scope.data = {
response:'{"id":"123456","post_id":"12345"}'
};
alert($scope.data);
alert($scope.data.response);
alert($scope.data.response.id);
$scope.temp = angular.fromJson($scope.data.response);
alert($scope.temp.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
</div>
</body>
var app = angular.module('myApp', []);
app.controller('list_employeesController', function($scope, $http) {
// email = $scope.email;
// psw = $scope.psw;
$http({
method: "GET",
url: "http://localhost:3000/employees",
params: {}
}).then(function mySuccess(response) {
// a string, or an object, carrying the response from the server.
$scope.myRes = response.data;
$scope.statuscode = response.status;
}, function myError(response) {
$scope.myRes = response.statusText;
});
});
Simply Here myRes has the response data to this request.
And we can display it in HTML file using expression syntax in angular
<h2> Result : {{myRes}} </h2>
var app = angular.module('myApp', []);
app.controller('student_Controller', function($scope, $http) {
$http({
method: "GET",
url: "http://localhost:8000/employees",
}).then(function mySuccess(response) {
$scope.res= response.data;
$scope.statuscode = response.status;
}, function myError(response) {
console.log("response--"+response);
});
});

How to load more than one json file in angular

I am wondering how to load multiple .json files in to template.
In my example I have submissions from users and I do not want to store everything in one json file if possible.
How to grab some data from multiple json files?
here is my plunk example
I want to load users.json as well
var app = angular.module('myApp', []);
app.directive('contentItem', function ($compile,$parse) {
templates = {
image: 'image.html',
event: 'event.html',
article: 'article.html',
ad: 'ad.html',
discount: 'discount.html',
video: 'video.html'
}
var linker = function(scope, element, attrs) {
scope.setUrl = function(){
return templates[scope.content.content_type];
}
}
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content: '='
},
templateUrl: 'main.html'
};
});
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'content.json';
$scope.content = [];
$scope.fetchContent = function() {
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
}
$scope.fetchContent();
}
Help appreciated
You can request for JSON either from the controller like:
app.controller('myController', function($scope, $http){
$scope.users = [];
$scope.getUsers = function() {
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).
success(function(data, status) {
$scope.users = data;
}).
error(function(data, status) {
console.log(data || "Request failed");
});
};
and the other approach (better one) would be to make use of angular factory to fetch the JSON file.
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
where now you can include this factory as a dependency and get the user data and assign that in the callback function.