Using AngularJS to consume REST - javascript

I've made a REST api using Flask which gives a JSON response on http://localhost:5000/api/person giving the id,names and phone numbers of all the people in a SQLite database. http://localhost:5000/api/person/Name_of_person gives the JSON response corresponding to a person's name. I want to use AngularJS to consume the API so that I can output the names of all the people along with their phone numbers.
index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.id }} + ', ' + {{x.name }} + ',' + {{x.phone}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:5000/api/person").then(function (response) {
$scope.myData = response.data.objects;
});
});
</script>
</body>
</html>
Contents of http://localhost:5000/api/person
{
"num_results": 5,
"objects": [
{
"id": 24,
"name": "Name2",
"phone": "9999192938"
},
{
"id": 23,
"name": "Name3",
"phone": "9999192938"
},
{
"id": null,
"name": "Name4",
"phone": "9999192938"
},
{
"id": 21,
"name": "Name5",
"phone": "9999192938"
},
{
"id": null,
"name": "Name6",
"phone": "9999192938"
}
],
"page": 1,
"total_pages": 1
}
I am pretty sure my syntax is correct but I am getting no output for index.html. Can anyone please explain where I am going wrong? Is it maybe because it is on a local server and is unable to retrieve the data?

Please test the api by REST client, if the API returns proper result.
If you are having problem in running the application, please test using firefox browser. For chrome you need to serve the index.html through any server as it blocks file:/// protocol and needs http:// to run properly.
Make sure your API supports CORS. You have to set it in API end (see Flask docs) or else you can use CORS plugin for chrome.
If still problem persists there might be any logical/syntactical error. Please paste/share screenshot of your browser console.

Related

Mapping variables in json output to position in string

How do I map the example in the json output to a string based on the position? It's rather difficult to explain, but I have included my code and further details below:
JSON output
[
{
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}",
"example": "the team",
"position": 0
},
{
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}",
"example": "match skills",
"position": 1
},
{
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}",
"example": "defence techniques",
"position": 2
}
]
controller.js
PhraseService.getPhraseExample($scope.phraseId).then(function(dataResponse) {
$scope.phraseExampleList = dataResponse.data;
})
services.js
function PhraseService($http) {
this.getPhraseExample = function(phraseId) {
return $http({
method: 'GET',
url: server + '/api/phrase-example/' + phraseId,
});
}
}
phrase-detail.html
<div class="item item-text-wrap">
<span ng-repeat="e in phraseExampleList">{{ e }}</span>
</div>
Current output
Desired output
You want something as described in https://stackoverflow.com/a/18234317/3856625 Seems that StackOverflow has the same method you need :)
So you would map over the entries you have and just use it to replace the needed.

Json response via http not working

Currently working on angularjs I am trying to get the data from JSON file and I am showing the result in Ul format. when I searched in SO I found this link I am trying to do the same but still I am not getting
This is what I am trying here in controller
'use strict';
var app = angular.module('myApp', []);
app.controller('MyController', function($scope, $http){
$http.get('sample.json').then(function (response){
$scope.items = response.data.countries;
});
});
HTML Code
<body ng-app="myApp">
<div ng-controller="MyController">
<ul>
<li ng-repeat="(key, value) in items" {{key}}>
</li>
</ul>
</div>
</body>
Here is my plunker kindly help me what i am doing wrong here
One other problem: your JSON is incorrect:
{
"countries": {
"State": [
"TamilNadu"
],
"State": [ <-- Error: duplicate key!
"Karnataka"
]
}
}
Here is an alternative:
{
"countries": [
{ "USA": [
{"State": "California"},
{"State": "Nevada"} ]},
{ "India": [
{"State": "TamilNadu"},
{"State": "Karnataka"} ]}
] }
There are three issues,
(i)You do not need to declare the module twice , once in script.js and other one
in controller.js.
(ii) You were refering to angular 2.0 version ,and coded using angular 1.4 version.
(iii)If you want to show all states from json, it should not have a duplicate key, which you could see from the plunker itself
{ "countries": {
"State": [
"TamilNadu"
],
"State": [ <-- Error: duplicate key!
"Karnataka"
] } }
Here is the working Application

Passing Json data from Controller to View in Angular JS to build a table

Trying to get the certain fields to display, ideally in a table (headings, rows & columns). And looking for a best way find fields in a Json feed. I tried using the controller to find the fields then pass that data to the view in the HTML.
Is there something wrong in the controller with respect to the Json? the fields are empty. Seems like nothing is passed from the controller to the view ? This is what I tried:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
}
};
$scope.elements = $scope.result.data.transactionList.map(function (res) {
var e = {};
e.transTypeId = res.transTypeId;
e.userId = res.userId;
e.storeId = res.storeId;
return e;
});
});
</script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from the JSON feed</h1>
<ul>
<li ng-repeat="e in elements">
{{ e.transTypeId}}: {{ e.userId }}, {{ e.storeId }}
</li>
</ul>
</body>
</html>
You have a extra } in your $scope.result. It should be like:
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
};
// get rid of this};
Here is working plunkr
Perhaps a }; too many?
Automatic indentation usually makes those kinds of errors apparent.
Have you tried to use ng-model="...", it gives you the opportunity to overwrite an attribute or to show it. You can try it with
<input type="number" ng-model="someID" disabled="disabled">
*disabled if u need readOnly on that field.
and see how it works, maybe it can help you out.
regards
I may be wrong, but you are trying to read json data directly without parsing it?
MDN JSON.parse()
Also it would be nice if you upload your code on something like http://jsfiddle.net
This way people can test it out.

http json file retrieving with IONIC and AngularJS

I am working on an product reviewing app based on ionic framework.
The app will consume REST service in JSON format.
Because Im not able to retireve data directly from the locally deployed website, i created a json demo file:
[{
"index": 0,
"marque": "labore",
"estAutorise": 0,
"name": "Jennifer Simmons"
},
{
"index": 1,
"marque": "duis",
"estAutorise": 0,
"name": "Beatriz Hale"
},
{
"index": 2,
"marque": "pariatur",
"estAutorise": 1,
"name": "Richmond Garner"
}
]
here is my services.js:
angular.module('starter.services', [])
.factory('Recettes', function($http) {
var recettes = [];
var produits = [];
$http.get('test.json').success(function(data) {
alert("success"); //to check the seccess responce
produits= data;
});
return {
...
produits: function() {
return produits;
},
....
Before this, I implemented products and recettes directly and it works just fine. And now, I recieve the success alert but the data seems to be invalid.
My controller:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, Recettes) {
$scope.produits = Recettes.produits();
})
...
So my question is how can i fix the data binding problem ?
And If it works with .json file should it work for rest services as well (Content-Type: application/json )?
Thank you.

Consuming a RESTful api with Restangular - Is it secure for a RESTful api to return an array as a top-level object?

I'm creating a RESTful web service using Python Flask. For one of my endpoints I'd like to return a list of users. The api endpoint returns JSON in the following format:
{
"users": [
{
"Email": "email1#example.org",
"First": "Tom",
"Last": "Jones",
"id": 1
},
{
"Email": "email2#example.org",
"First": "Steven",
"Last": "Fry",
"id": 2
},
{
"Email": "email3#example.org",
"First": "Monty",
"Last": "Python",
"id": 3
}
]
}
If I do this Restangular responds with
Error: Response for getList SHOULD be an array and not an object or
something else
which is by design as Restangular expects an Array and not a Javascript object. From what I understand there are two preferred options for dealing with this:
Option 1 - Wrap the response in an array like so:
[{
"users": [
{
"Email": "email1#example.org",
"First": "Tom",
"Last": "Jones",
"id": 1
},
{
"Email": "email2#example.org",
"First": "Steven",
"Last": "Fry",
"id": 2
},
{
"Email": "email3#example.org",
"First": "Monty",
"Last": "Python",
"id": 3
}
]
}]
However, according to this article http://flask.pocoo.org/docs/0.10/security/#json-security this is not secure. Is my understanding correct here?
Option 2 - The second option is to use this method: https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case
In this case is it possible (would I need to?) to create an interceptor for every getList request on all endpoints that return multiple items e.g. a 'posts' endpoint, 'messages' endpoint etc.? Would this be a feasible or good approach?
Is there anything I'm missing in my understanding?
Option 1 seems like less work but potentially introduces a security concern. Option 2 would be more work but mitigates the potential security problem (if there is one).
If there's an even better 'Option 3' it would be great to hear it!
You can set isArray equals false, and handle your request normally check https://github.com/mgonto/restangular/issues/85

Categories

Resources