Angularjs and Web Services - json

I make a web services which returns me a JSON formatted data when I use this url(http://localhost:8080/jerseyweb/crunchify/ftocservice). Now I want to get those data through Angular js but I can not get it. The code with which I try that is as follow:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.id + ', ' + x.name }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
alert("hi");
$http.get("http://localhost:8080/jerseyweb/crunchify/ftocservice")
.success(function (data, status, headers, config) {
alert("hiee"); // i can not reach at this alert
$scope.names = data;
});
});
</script>
</body>
</html>
The JSON data in http://localhost:8080/jerseyweb/crunchify/ftocservice is as following
[{"id":98.24,"name":36.8}]

There is an error in Web Services Response.....
#OPTIONS
#Path("/getsample")
public Response getOptions() {
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.build();
}

Please try this code might be it's use full :
var response = $http({
method: "GET",
url: "http://localhost:8080/jerseyweb/crunchify/ftocservice",
dataType: "json"
});
response.then(function (obj) {
$scope.names = obj.data.name;
}, function () {
alert('Error.');
});
If data comes from the API in string format then use
var objdata = JSON.parse(obj.data);
$scope.names = objdata.name;

Related

Call angular function inside ng-repeat and return array

I searched for this but I did not get any answer as I want, please give me a solution, I want to use ng-init inside ng-repeat, ng-init should give me different response at every loop here is my HTML
<html>
<body ng-app="crmApp">
<div ng-controller="customerDetailController">
<div ng-repeat="clientDetail in client">
<p>{{clientDetail.name}}</p>
<div ng-init="seoDetails = getCustDetail(clientDetail.name)">
<p>{{seoDetails.cust_Name}}</p>
</div>
</div>
</div>
</body>
</html>
and my js is
<script>
var crmMain = angular.module('crmApp', ['ngRoute','ngMaterial']);
crmMain.controller('customerDetailController',function customerDetailController($scope, $http, customerDetailFactory,$window) {
$scope.client = [];
$scope.init = function () {
$scope.getCustomerData();
};
$scope.getCustomerData = function () {
customerDetailFactory.getCustomerDetailData().then(function
(response) {
$scope.client = response.data;
});
};
$scope.getCustDetail = function (Name) {
var custDetail = [];
custDetail = customerDetailFactory.getCustomerDetailData(Name).then(function (response) {
alert(response.data.cust_Name);
return response.data;
});
return custDetail;
};
$scope.init();
});
crmMain.factory('customerDetailFactory', ['$http', function ($http) {
var factory = {};
var url = 'phpFile/customerDetail.php';
factory.getCustomerDetailData = function (Name) {
return $http({
method: 'POST',
url: url,
data: {
'functionName': 'clientDetailPage',
'customerName': Name
}
});
};
return factory;
}]);
</script>
In inside getCustDetail function I was given alert in there it 'll show name, but I don't know why it not showing in HTML.is anything wrong I did?
I have got one solution for this, I think I have to use Promises for this, but I don't know how to use it can anyone help me in this?
You cannot use ng-init for this purpose.
You've to do the data fetching inside the controller itself. That is like,
customerDetailFactory.getCustomerDetailData()
.then(function(response) {
$scope.client = response.data;
// for each clients, fetch 'seoDetails'
$scope.client.forEach(function(client) {
customerDetailFactory.getCustomerDetailData(client.name)
.then(function (response) {
// I hope response.data contains 'cust_Name'
client.seoDetails = response.data;
})
});
});
Now, in the view, you can directly use the seoDetails property
<div ng-repeat="clientDetail in client">
<p>{{clientDetail.name}}</p>
<p>{{clientDetail.seoDetails.cust_Name}}</p>
</div>

AngularJS databinding through responsemessage not working as expected

Code is as follows
var myApp = angular.module("gameModule", []);
myApp.controller("gamecontroller", function ($scope) {
$scope.message = "test";
// websocket connection.
var gameHub = $.connection.socketHub;
$.connection.hub.start().done(function () {
var clientid = $.connection.hub.id;
$(function () {
var user = { signalrsessionid: clientid };
$.ajax({
type: "POST",
data: JSON.stringify(user),
url: "http://localhost:53629/api/game/signalr",
contentType: "application/json"
}).done(function (response) {
alert(response);
$scope.responsemessage = response;
});
});
});
});
and front end code
<!DOCTYPE html>
<html ng-app="gameModule">
<head>
<title>game registration</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.js"></script>
<script src="Scripts/angular.js"></script>
<!--Automatisch gegenereerde signalR hub script -->
<script src="signalr/hubs"></script>
<script src="Scripts/rouletteAngular.js"></script>
</head>
<body>
<div ng-controller="gamecontroller">
{{ message }}
{{ responsemessage }}
</div>
So the 'message' is being displayed, the alert box with the response is showing the correct response, but the responsemessage doesnt show any value.
Can anyone tell me what i'm doing wrong.
you must call $scope.$apply(); or $scope.$digest(); after setting $scope.responsemessage = response; because you are using jQuery ajax call, which is outside Angulars context.
EDIT:
here you have nice way to use SignalR in AngularJS:
http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html

json value not fetching from localhost to angularjs frontend

This my javascript part i am not able to get any response from $http.get
can anyone suggest a solution
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:3000/load")
.success(function(response) {$scope.names = response;});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="data in names">
{{ data.name + ', ' + data.age }}
</li>
</ul>
</div>
From AngularJS documentation https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
No localhost:3000, just use '/load'.
No '.success', use '.then'
Try this
var Response = $http.get( $window.location.pathname + your url); //put your url here
Response.success( function ( data ) {
$scope.Names = data;
} );
Response.error( function ( data ) {
$scope.error = data;
} );
Your angular code has to change like #Dmitri Algazin has suggested. Check below code and the JS Fiddle
$http.get("http://localhost:3000/load")
.then(function(response) {$scope.names = response.data;});
JSfiddle

How is possible to load some setting from .json file before angular app starts

i'm building application which uses CORS requests. Each request i use get host address from a constant
angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
And in each service i use to send request like this:
angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
var baseurl = baseUrl.server ;
$http.get(baseurl + 'document')
Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory?
I mean : how can i load something from ajax request an make it accessible to app modules
i have tried:
.run(['$rootScope', , function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
});
And tried to access it from baseUrl:
angular.module('siteApp').factory('baseUrl',function($rootScope) {
return {
server: $rootScope.HOST
But no luck - the baseUrl.server comes undefined into functions
You can use run method of angular.
var app = angular.module('plunker', []);
app.run(function($http, $rootScope){
$http.get('config.json')
.success(function(data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function(data, status, headers, config) {
// log error
alert('error');
});
})
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('config-loaded', function(){
$scope.name = $rootScope.config.name;
});
});
see this plunker
If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.
From:
https://docs.angularjs.org/api/ng/function/angular.bootstrap
<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('demo', [])
.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
// Do your loading of JSON here
angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
You need to tell angular about data change, so modify your code something like this:
.run(['$rootScope', function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
$rootScope.$apply(); // New line
});
}])
That $apply() is needed since its a non-angular asynchronous call.
use the blow code snippet to load the json values
.run(function ($http, $rootScope) {
$http.get('launchSettings.json')
.success(function (data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function (data, status, headers, config) {
// log error
alert('error');
});
});

how to use JSONP in AngularJS resource

I'm trying to import json object into variable. I use the services according to tutorial.
I receive unexpected token error, because i shouldn't use $scope.news = JsonSource.feed(); - but I really don't know what should I use. I googled and searched 3 hours I find only $http. or $json. answers, but I feel, that it could be done easier - clearer.
(The perfect solution would be $scope.news = JsonSource.feed().entries ;D
The services file:
var AAAServices = angular.module('AAAServices', [
'ngResource'
]);
AAAServices.factory('JsonSource', ['$resource',
function($resource) {
return $resource('https://www.facebook.com/feeds/page.php', {}, {
feed: {method:'JSONP', {format: 'json', id:'459908', callback : JSON_CALLBACK}, isArray:false}
});
}]);
The controllers file:
var AAAControllers = angular.module('AAAControllers', [])
AAAControllers.controller('newsCtrl', ['$scope', 'JsonSource',
function newsCtrl($scope, JsonSource) {
$scope.news = JsonSource.feed();
}]);
the json file (almost ;D)
{
"title": "Tytuł",
"link": "https:\/\/www.facebook.com\/",
"entries": [
{
"title": " news 1",
"id": "1"
},
{
"title": " news 2",
"id": "2"
}
]
}
Edited:
i change $resource('file.json into https://www.facebook.com/feeds/page.php - so you can check if it is json or jsonp...
I did not notice that it takes to be a JSONP, so I did it with default $resource method.
Below is an example that does what you want.
Please remember to:
include a file angular-resource.min.js
inject ngResource to services module
inject motoAdsServices to app module
inject Brand to controller
the rest will do Angular :)
index.html
<!DOCTYPE html>
<html ng-app="motoAdsApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script type="text/javascript" src="controllers.js"></script>
<script type="text/javascript" src="services.js"></script>
</head>
<body>
<div ng-controller="AdvertsController">
<label>Brand</label>
<select name="brand" ng-model="brand" ng-options="b.name for b in brands">
<option value=""></option>
</select>
</div>
</body>
</html>
services.js
var motoAdsServices = angular.module('motoAdsServices', ['ngResource']);
motoAdsServices.factory('Brand', ['$resource', function($resource) {
return $resource('./brands.json', {}, {});
}]);
controllers.js
var motoAdsApp = angular.module('motoAdsApp', ['motoAdsServices']);
motoAdsApp.controller('AdvertsController', ['$scope', 'Brand',
function($scope, Brand) {
$scope.brands = Brand.query();
}]);
brands.json
[
{"name": "Audi", "models": [{"name": "A1"}, {"name": "A3"}, {"name": "A4"}]},
{"name": "BMW", "models": [{"name": "Series 3"}, {"name": "Series 5"}, {"name": "Series 7"}]},
{"name": "Citroen", "models": [{"name": "C1"}, {"name": "C2"}, {"name": "C3"}]},
{"name": "Dacia", "models": [{"name": "Duster"}, {"name": "Logan"}, {"name": "Sandero"}]}
]
Plunker example
UPDATE (because should be JSONP)
To use JSONP you should only change services.js
var motoAdsServices = angular.module('motoAdsServices', ['ngResource']);
motoAdsServices.factory('Brand', ['$resource', function($resource) {
return $resource('./brands.json', {}, {
jsonpquery: { method: 'JSONP', params: {callback: 'JSON_CALLBACK'}, isArray: true }
});
}]);
and controllers.js
var motoAdsApp = angular.module('motoAdsApp', ['motoAdsServices']);
motoAdsApp.controller('AdvertsController', ['$scope', 'Brand',
function($scope, Brand) {
$scope.brands = Brand.queryjsonp();
}]);
And it shoould be work. But server should return valid jsonp.
There is the same problem:
jsonp request with angular $resource
And he found that there was a problem with server.
UPDATE 2 (because the problem is probably with CORS in node.js server)
server.js (node.js)
var express = require('express');
var path = require('path');
var http = require('http');
var brands = require('./routes/brands');
var countries = require('./routes/countries');
var adverts = require('./routes/adverts');
var app = express();
// ALLOW CORS!!!
var allowCrossDomain = function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
};
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(allowCrossDomain);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/api/brands', brands.findAll);
app.get('/api/countries', countries.findAll);
app.get('/api/adverts', adverts.findAll);
http.createServer(app).listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'));
});
routes/brands.js
exports.findAll = function(req, res) {
var fs = require('fs');
var file = './server/data/brands.json';
fs.readFile(file, 'utf8', function(err, data) {
if (err) {
throw err;
}
res.send(JSON.parse(data));
});
};
UPDATE 3 (because CORS should be added to web-server.js (node.js) without express)
You have something like:
https://github.com/angular/angular-seed/blob/master/scripts/web-server.js
So you have to add ALLOW CORS (look below I added 2 lines) to response headers:
StaticServlet.prototype.sendFile_ = function(req, res, path) {
var self = this;
var file = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': StaticServlet.
MimeMap[path.split('.').pop()] || 'text/plain',
// ALLOW CORS - line 1 !!!
'Access-Control-Allow-Origin' : '*',
// ALLOW CORS - line 2 !!!
'Access-Control-Allow-Headers': 'X-Requested-With'
});
if (req.method === 'HEAD') {
res.end();
} else {
file.on('data', res.write.bind(res));
file.on('close', function() {
res.end();
});
file.on('error', function(error) {
self.sendError_(req, res, error);
});
}
};
Maybe you have other function with jsonp, so add to res.writeHead(200, CORS headers too.
UPDATE 4 - ANGULARJS CALL FACEBOOK BY JSONP
THIS SOLUTION SHOULD BE WORK !!!
services.js
var myServices = angular.module('myServices', ['ngResource']);
myServices.factory('FacebookFeed', ['$resource',
function($resource) {
return $resource('https://graph.facebook.com/cocacola?callback=JSON_CALLBACK', {}, {
jsonp_query: {
method: 'JSONP'
}
});
}
]);
controllers.js
var myApp = angular.module('myApp', ['myServices']);
myApp.controller('MyController', ['$scope', 'FacebookFeed',
function($scope, FacebookFeed) {
$scope.feeds = FacebookFeed.jsonp_query();
console.log()
}]);
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script type="text/javascript" src="controllers.js"></script>
<script type="text/javascript" src="services.js"></script>
</head>
<body>
<div ng-controller="MyController">
<label>Facebook feeds</label></label>
<pre>{{feeds}}</pre>
</div>
</body>
</html>
Plunker example
This is the answer for those, who thinks (as me) that if something works in browser it should work in server scripts.
facebook gives very nice json for the wall content:
https://www.facebook.com/feeds/page.php?format=json&id=xxxx
But you can't get it from nodejs - because of cross domain policy-restriction
More about is here: Loading facebook wall feed JSON issues
So, now i have to search for jsonp stream for facebook wall... Sigh....