Displaying json data in angularjs - json

I would like to display data returned from service call into view:
Service Code :
.service('HomeExchangeList', function ($rootScope, $http, $log) {
this.getHomeExchange = function() {
var rates = $http({
method: 'GET',
url: 'http://localhost:8080/feeds/homerates_android.php'
}).success(function (data) {
$log.log(data);
return data;
});
return homeRates;
};
})
JSON Data returned by service
{
"record":[
{
"Name":"GBP\/USD",
"Ticker":"GBP\/USD",
"Price":"0.5828",
"Open":"0.5835",
"High":"0.5848",
"Low":"0.5828",
"PercentagePriceChange":"0.1371",
"Movement":"0.0800",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"EUR\/USD",
"Ticker":"EUR\/USD",
"Price":"0.7330",
"Open":"0.7344",
"High":"0.7351",
"Low":"0.7327",
"PercentagePriceChange":"0.2585",
"Movement":"0.1900",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"GHS\/USD",
"Ticker":"GHS\/USD",
"Price":"3.3350",
"Open":"3.2650",
"High":"3.3500",
"Low":"3.2650",
"PercentagePriceChange":"0.8915",
"Movement":"3.0000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"KES\/USD",
"Ticker":"KES\/USD",
"Price":"87.7000",
"Open":"86.2970",
"High":"87.6500",
"Low":"86.1800",
"PercentagePriceChange":"0.0661",
"Movement":"5.8000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"MUR\/USD",
"Ticker":"MUR\/USD",
"Price":"30.2925",
"Open":"29.1460",
"High":"29.4300",
"Low":"29.0500",
"PercentagePriceChange":"-0.0909",
"Movement":"-2.7500",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"MWK\/USD",
"Ticker":"MWK\/USD",
"Price":"393.5000",
"Open":"393.3900",
"High":"393.3900",
"Low":"385.0000",
"PercentagePriceChange":"-0.2548",
"Movement":"-100.0000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"NGN\/USD",
"Ticker":"NGN\/USD",
"Price":"162.3000",
"Open":"160.0600",
"High":"162.4000",
"Low":"160.0600",
"PercentagePriceChange":"0.2459",
"Movement":"40.0000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"ZAR\/USD",
"Ticker":"ZAR\/USD",
"Price":"10.6659",
"Open":"10.6751",
"High":"10.7162",
"Low":"10.6523",
"PercentagePriceChange":"0.9840",
"Movement":"10.6000",
"DateStamp":"2014\/07\/09",
"TimeStamp":"22:15:00"
},
{
"Name":"ZMK\/USD",
"Ticker":"ZMK\/USD",
"Price":"47.7014",
"Open":"47.3850",
"High":"47.7000",
"Low":"46.8900",
"PercentagePriceChange":"0.0067",
"Movement":"0.3165",
"DateStamp":"2013\/07\/27",
"TimeStamp":"01:55:00"
}
]
}
Controller code
function HomeCtrl($scope, Page, $location, HomeExchangeList) {
$scope.rates = HomeExchangeList.getHomeExchange();
$scope.$on('HomeExchangeList', function (event, data) {
$scope.exchangeRates = data;
});
}
View
<ul id="home-rates" ng-repeat="rate in exchangeRates">
<li><span class='rate-symbol'>{{rate.Name}}</span><span class='rate-amount'>{{rate.Price}}</span></li>
</ul>
I would like to display the data returned by in the service in the view but it doesn't seem to be working. Please help

First, $http invocations all return a promise, not the result of your request. Your service should just return the result of the $http call, and your controller needs to attach a .success handler to receive the data and set it on the scope of your controller.
.service('HomeExchangeList', function ($rootScope, $http, $log) {
this.getHomeExchange = function() {
var rates = $http({
method: 'GET',
url: 'http://localhost:8080/feeds/homerates_android.php'
}).success(function (data) {
$log.log(data);
// removed your return data; it doesn't do anything, and this success is only added to log the result. if you don't need the log other than for debugging, get rid of this success handler too.
});
return rates;
};
})
function HomeCtrl($scope, Page, $location, HomeExchangeList) {
HomeExchangeList.getHomeExchange().success(function(data) {
$scope.exchangeRates = data;
});
}
Second, the root of your JSON is not an array, so you can't enumerate through just exchangeRates alone. Perhaps you meant exchangeRates.record.

try to assign data.record to $scope.exchangeRates instead of data... as data doesnt hold the array of records... it holds record which then holds the array

First of all, your service function always returns undefined:
var rates = ...,
return homeRates;
It should be
return rates;
Second, once that is fixed, the service doesn't return data. It returns a promise, and you can't iterate on a promise. What you need in the controller is:
HomeExchangeList.getHomeExchange().then(function(data) {
$scope.rates = data.record;
}
The call to $scope.$on doesn't make any sense. $scope.$on is used to listen for events. Not to get data from a promise.
And finally, your view must iterate over these retes, and not over exchangeRates:
ng-repeat="rate in rates">

Related

Reactjs assigning state variable to output of function (undefined)

Using ReactJS, I have a function that hits a weather API and returns data.
I am trying to assign 'this.state.results' to the output of the function however it doesn't get assigned and console.log(this.state.results) returns 'undefined'
Here is the function:
searchCity: function(){
jsonp('https://autocomplete.wunderground.com/aq?query=lond', { param: 'cb' }, function (err, data) {
return (data.RESULTS);
})
}
Here is the function that calls the function and assigns the 'results' variable to the output. i've included initialState function just for reference.
getInitialState: function() {
return {
value: "",
results: "hello"
}
},
searchAPI: function(){
this.setState({results: apiHelpers.searchCity()})
}
However 'results' is not getting assigned.
Any help appreciated!
You need to return something from the function searchCity().
Try this:
searchCity: function(){
return jsonp('https://autocomplete.wunderground.com/aq?query=lond', { param: 'cb' }, function (err, data) {
return (data.RESULTS);
})
}

How can I send requests to JSON?

I'm coding a mobile application with ionic. I have to get a data (daily changing data) from a web page with JSON, but I want to get old data too. For example:
data.json?date=2016-11-10
data.json?data=2016-12-10
How can I send request to JSON?
To send data from PHP, once you get your data from the database, the array will apply json_encode($array); and to return you put return json_encode ($ array);
Try this!
var date = '2016-11-10';
$http({
method: 'GET',
url: data.php,
params: {date: date},
dataType: "json",
contentType: "application/json"
}).then(function(response) {
});
The question is confusing, so I'm not sure how to answer. If you are having trouble formatting a request to a REST service, you will need to find out how the service expects the date to be formatted in your field-value pair i.e:
date=2016/11/10 or date=20161110
If those don't work, this answer may help The "right" JSON date format
However, if you are actually wondering how to serialize a date in JSON, this link may help http://www.newtonsoft.com/json/help/html/datesinjson.htm
I prefer to use services for ajax requests.
Create a Service
//Service
(function() {
'use strict';
angular
.module('appName')
.factory('appAjaxSvc', appAjaxSvc);
appAjaxSvc.$inject = ['$http', '$log', '$q'];
/* #ngInject */
function appAjaxSvc($http, $log, $q) {
return {
getData:function (date){
//Create a promise using promise library
var deferred = $q.defer();
$http({
method: 'GET',
url:'/url?date='+date
}).
success(function(data, status, headers,config){
deferred.resolve(data);
}).
error(function(data, status, headers,config){
deferred.reject(status);
});
return deferred.promise;
},
};
}
})();
Then Use it in Controller
(function() {
angular
.module('appName')
.controller('appCtrl', appCtrl);
appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];
/* #ngInject */
function appCtrl($scope, $stateParams, appAjaxSvc) {
var vm = this;
vm.title = 'appCtrl';
activate();
////////////////
function activate() {
appAjaxSvc.getData(date).then(function(response) {
//do something
}, function(error) {
alert(error)
});
}
}
})();

ng-tags-input autocomplete is not displayed

I try to use ng-tags-input with a returned Json list by an api controller .net Mvc 6. My list is created in json but when try to display this list with the autocompletion , nothing works. My autocomplete list isn't displayed and I don't have error in chrome console.
So this is an object of my list :
[{
"ShopID":1,
"CompanyID":1,
"RegionID":1,
"Name":"Les Pieux",
"Town":"Les Pieux",
"Address":null,
"ZipCode":null,
"CreateDate":"2006-01-01T00:00:00",
"ModificationDate":"2006-09-29T00:00:00",
"LastModificationUserID":1,
"PhoneNumber":null,
"Fax":null,
"Email":null,
"CEmployeeShop":null
}]
This is my method in my controller:
$scope.tokenShops = [];
$scope.loadJsonShops = function(query)
{
//$scope.shops contains my list of shops in json format.
return $scope.shops;
}
And the tag in Html:
<div ng-controller="EmployeesCtrl">
<tags-input ng-model="tokenShops"
display-property="Name"
Placeholder="Ajouter un magasin"
add-from-autocomplete-only="true">
<auto-complete resource="loadJsonShops($query)"></auto-complete>
</tags-input>
</div>
This is my code that populates $scope.shops
Api Controller:
public IEnumerable<Shop> Get()
{
using (LSContext db = new LSContext())
{
var listShop = db.Shops.ToList();
return listShop;
}
}
angular shopCtrl:
function ShopsCtrl($scope, $http, $rootScope) {
function getShopsList() {
var reqGetShops = $http({ url: 'api/Shops' });
reqGetShops.success(function (data) {
$scope.shops = data;
$rootScope.$broadcast("getListShops", { list: data });
});
}
//with api controller the list is returned in json format. I tried an another method to fill my list with an convertion that I do and it doesn't work.
angularjs EmployeeCtrl :
$scope.$on("getListShops", function (event, args) {
$scope.shops = args.list;
$scope.selectShop = args.list[0];
})
But I don't think that my problem from my json list.
I hope someone can help me . Have a nice day.
I resolve my problem with a directive:
angular.module('TagsDirective', ['myResources', 'resourcesManagerGet', 'translateI18n'])
.directive('tags', function ($http, $q) {
return {
restrict: 'E',//restraint pour les éléments du dom
template: '<tags-input ng-model="SShops" key-property="ShopID" display-property="Name" placeholder="{{\'AddShop\' | i18n}}" add-from-autocomplete-only="true"><auto-complete source="loadTags($query)"></auto-complete></tags-input>',
scope: false,
link: function (scope, el) {
scope.loadTags = function (query) {
var deferred = $q.defer();
var reqGetShops = $http({ url: 'api/Shops/GetListShopFiltered', params: { 'query': query } });
reqGetShops.success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
}
}
});
and in Html:
<tags></tags>
g0loob : thanks for your help, but now you can put an array of objects and use the attribute display-property to choose the text property to display.
example:http://mbenford.github.io/ngTagsInput/demos and look the tags input with custom object.
auto-complete requires array of objects with at least one property named "text" (just like tags-input), if you are not using your template for auto-complete or tags-input. And you also need to filter your result for auto-complete in order to work properly. Also see this link.
angular.module('TagsDirective', ['myResources', 'resourcesManagerGet', 'translateI18n'])
.directive('tags', function ($http, $q) {
return {
restrict: 'E',//restraint pour les éléments du dom
template: '<tags-input ng-model="SShops" key-property="ShopID" display-property="Name" placeholder="{{\'AddShop\' | i18n}}" add-from-autocomplete-only="true"><auto-complete source="loadTags($query)"></auto-complete></tags-input>',
scope: false,
link: function (scope, el) {
scope.loadTags = function (query) {
var deferred = $q.defer();
var reqGetShops = $http({ url: 'api/Shops/GetListShopFiltered', params: { 'query': query } });
reqGetShops.success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
}
}

Displaying nested JSON with angularjs

I am trying to display nested JSON in a page. I'm not sure how to drill down into it.
In my app js file I have an parameter called initialData that I want to call a function getProducts() when the view is called...
'use strict';
var quoteApp = angular.module('quoteApp', ['ui.router']);
quoteApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'ng-views/choose.html',
controller: "quoteBuilderController",
resolve: {
initialData: ['quoteApi', function (quoteApi) {
return quoteApi.getProducts();
}]
}
})
});
my quoteApi looks like this in case you want to see it...
(function () {
'use strict';
angular.module('quoteApp').factory('quoteApi', quoteApi);
quoteApi.$inject = ['$http'];
function quoteApi($http) {
var service = {
getProducts: getProducts,
getPrices: getPrices
};
var baseUrl = 'http://www.website.com/api/Pricing';
return service;
function getProducts() {
return httpGet('/GetProductCatalogue');
}
function getPrices() {
return httpGet('/GetPrices');
}
/** Private Methods **/
function httpExecute(requestUrl, method, data){
return $http({
url: baseUrl + requestUrl,
method: method,
data: data,
headers: requestConfig.headers }).then(function(response){
return response.data;
});
}
function httpGet(url){
return httpExecute(url, 'GET');
}
}
})();
So quoteApi.getProducts() returns JSON that looks like this...
{
"Cat1": [
{
"product_id": 1,
"product_name": "Prod1"
},
{
"product_id": 2,
"product_name": "Prod2"
}
],
"Cat2": [
{
...
}
]
}
My controller for the view looks like this...
(function () {
'use strict';
angular.module('quoteApp').controller('quoteController', ['$scope', '$http', '$timeout', quoteController]);
quoteController.$inject = ['initialData', 'quoteApi'];
function quoteController($scope, initialData) {
$scope.cat1Products = initialData;
};
})();
So my question is, how can I get 'initialData' to load products from Cat1 only? Should I try to do this from the html? It seems like it should be straight forward enough but I can seem to get it. Thank you.
You need to transform your response from your http request further so you only return the piece you require, and you may also want to consider using the .then() approach:
$http.get('/someUrl').then(function(response) {
//Do something with response.data.Cat1 here
}, function(errResponse) {
console.error('Error while fetching data');
});
Just take out cat1 from your initialData object
function quoteController($scope, initialData) {
$scope.cat1Products = initialData['Cat1'];
};

to pass parameter to web api through ajax call

I have below ajax query which returns me json from controller
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=1",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
the controller action is as below
[System.Web.Http.ActionName("GetHomeTab")]
public HomeTabModel GetHomeTab(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new HomeTabModel
{
HomeDesc = outlet.BizHomeDesc,
HomeTabText = outlet.BizHomeTabText
};
}
Now my question is: curently i am sending hard coded value of bizId to web api. I want to send this value dynamically. How can i achieve this? I have that value in my route config file. The code is as below-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);
}
I am new to this. Please help! Thanks in advance!
no, actually after much research, i came up with this solution and this works fine for me....
In controller,
public ActionResult Index(int bizId)
{
ViewBag.BizId = bizId;
return View();
}
and in View,
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=#ViewBag.BizId",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
You can pass a data object as part of the GetJson call.
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab",{bizId : 1},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
Taking this one step further you could wrap this in a function.
function makeCall(id)
{
$.getJSON("api/OutletPOC/GetHomeTab",{bizId : id},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
}
Also look into using promises.
$.getJSON().then().done();