Angular js does not get json response from node js - javascript

I am trying to establish REST connection between node (middleware) and angular (UI). However, the json is displayed on the browser rather than being routed via the angular controller/html
Node/Express router.js
router.get('/members', function(request, response){
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST");
response.setHeader('Content-Type', 'application/json');
var dbdata = [];
var str;
db.get('_design/views555/_view/app_walltime', function (err, body) {
if (!err) {
body.rows.forEach(function(doc) {
dbdata.push({name: doc.key, walltime:doc.value});
});
console.log(dbdata);
response.json(dbdata);
Angular controllers.js
'use strict';
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.config(['$httpProvider', function($httpProvider, $routeProvider, $locationProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http, $templateCache) {
alert('asdsad');
$scope.list = function() {
alert('hereh');
var url = 'http://192.168.59.103:8072/members';// URL where the Node.js server is running
$http.get(url).success(function(data) {
alert(data);
$scope.phones = data;
});
};
$scope.list();
});
html - testangular.js
<html ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css">
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-route/angular-route.min.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<!--<p>{{phone.walltime}}</p> -->
</li>
</ul>
</div>
</div></div>
What is see is the following on the browser
[{"name":"app1","walltime":"1050"},{"name":"app2","walltime":"30"}]
I seem to be missing some configuration to let node and angular communicate. Please let me know what I am doing wrong.

What you see on the browser's window is a JSON object, that is the result of your request.
With the line $scope.phones = data;, you're simply assigning to $scope of Angular the data object, without actually parsing it.
The result is that Angular is not able to understand in the ng-repeat directive what actually {{phone.name}} and {{phone.walltime}} are and the JSON string is shown.
In order to have the ng-repeat directive working as expected, you have to parse first the JSON object, process it (creating for example a custom object and assigning its properties) and then assign it to $scope object.
You could perform the parse using something like
JSON.parse(data);.
Please have a look at this question for further information.
Or even using the Angular's builtin function angular.fromJson(data).
An example could this:
$http.get(url).success(function(data) {
alert(data);
$scope.phones = angular.fromJson(data);
});
};

Test this :
var url = 'http://192.168.59.103/members';
$http.get(url).then(
function(response) {
console.log('success',response)
},
function(data) {
// Handle error here
})

Related

MVC Controller method call from Angularjs return View HTML instead of JSON result

I have the following Controller method under HomeController,
[HttpGet]
public ActionResult GetStudents()
{
Student std1 = new Student();
List<Student> stdlst = new List<Student>();
std1.Id = 1;
std1.Name = "Emmanuvel";
std1.Age = 25;
stdlst.Add(std1);
Student std2 = new Student();
std2.Id = 2;
std2.Name = "Michael";
std2.Age = 24;
stdlst.Add(std2);
Student std3 = new Student();
std3.Id = 3;
std3.Name = "Hannah";
std3.Age = 22;
stdlst.Add(std3);
return Json(stdlst, JsonRequestBehavior.AllowGet);
}
And I'm calling this method using Angularjs Ajax function as below,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
$http.get('#Url.Action("GetStudents","Home")')
.success(function (data) {
$scope.students = data;
console.log($scope.students);
})
.error(function (data) {
console.log(data);
});
}
});
</script>
unfortunately, the console.log printing the View Page's HTML code, instead of the JSON data. Here is the console.log output,
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Submit" ng-click="ButtonClick()"/>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
$http.get('/Home/GetStudents')
.success(function (data) {
$scope.students = data;
console.log($scope.students);
})
.error(function (data) {
console.log(data);
});
}
});
</script>
</body>
</html>
Help me to understand the wrong I did in this code.
there are a number of changes I would do there.
First separate the angular code from your view. You probably did it to be able to use the Razor syntax to build the URL but now you have a dependency on that.
What I would do is this :
move the angular controller into it's own file.
change the JavaScript URL to '/Home/GetStudents'
change the return type of your backend controller to JsonResult, instead of ActionResult. Even if you are passing Json in the result, because it's ActionResult, it will still come back with the HTML of the page.
Once you do all this, first check in the browser that you are receiving the proper data by calling the '/Home/GetStudents' URL yourself. Once you are sure, then add some breakpoints and make sure Angular is receing the data properly and then continue from there.

Fetching JSONP with Angular.js

<html ng-app="movieApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var base = 'http://api.themoviedb.org/3';
var service = '/movie/862';
var apiKey = '####';
var callback = 'JSON_CALLBACK';
var url = base + service + '?api_key=' + apiKey + '&callback=' + callback;
var movieApp = angular.module('movieApp', []);
movieApp.controller('MovieCtrl', function ($scope, $http){
$http.jsonp(url).then(function(data) {
$scope.movies = data;
});
});
</script>
</head>
<body style="padding:12px;" ng-controller="MovieCtrl">
<div ng-repeat="movie in movies">
<h1>{{movie.title}} {{movie.id}}</h1>
<p>{{movie.overview}}</p>
<img ng-src="http://image.tmdb.org/t/p/w500{{movie.poster_path}}" style='width:200px'/>
</div>
</body>
</html>
Trying to fetch JSON with Angular.js. The information is coming across fine but statuses I believe is also coming across. Resulting in 5 images being placed on the screen, 4 broken and 1 good image along with the data. How can I avoid sending this extra data?
Requesting JSON data with AJAX
You wish to fetch JSON data via AJAX request and render it.
Implement a controller using the $http service to fetch the data and store it in the scope.
<body ng-app="MyApp">
<div ng-controller="PostsCtrl">
<ul ng-repeat="post in posts">
<li>{{post.title}}</li>
</ul>
</div>
</body>
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
$http.get('data/posts.json').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/requesting-json-data-with-ajax.html

AngularJS factory dependencies

I'm using AngularJS to extract information stored in mongodb. I'm trying to use a factory to retrieve that information using $http . I read so much information about how to do it, and no one works for me.
Also I'm using node + express, the routes works fine. The problem is the factory and the dependencies.
The only thing I need is:
Extract information stored in mongodb.
Store that information in a controller.
Show that information in the main page of my app.
index.html
<!doctype html>
<html ng-app="angular-blog">
<head>
<title> Angular blog </title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- AngularJS and JQuery include. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="./css/article.css" ></link>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"></link>
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"></link>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<menu-bar></menu-bar>
<div class="container" ng-controller="ArticleController as articleCtrl">
<h2> Blog </h2>
<div class="col-sm-4" ng-repeat="elem in articleCtrl.list">
<h4>{{ elem.title }}</h4>
<p> {{ elem.desc }} </p>
</div>
</div>
<!-- Custom controller. -->
<script src="./js/controllers/article.js"></script>
</body>
</html>
article.js
(function (){
var app = angular.module ('angular-blog', []);
app.directive ('menuBar', function (){
return {
restrict : 'E',
templateUrl : '../templates/menu-bar.html'
};
});
app.service ('articleFactory', ['$q', '$http', function ($q, $http){
this.getAllArticles = function (){
var deferred = $q.defer(),
httpPromise = $http.get ('/entries');
httpPromise.success (function (data){
deferred.resolve (data);
})
.error (function (err){
console.log (err);
});
return deferred.promise;
}
}]);
app.controller ('ArticleController', ['$http', 'articleFactory', function ($http, articleFactory){
this.article = {}; // Simple article.
this.list = []; // Article list.
this.list = articleFactory.getAllArticles()
.then (function (data){
return data;
}, function (err){
console.error (err);
});
this.addArticle = function (){
$http.post ('/addEntry', this.article)
.success (function (data){
console.log (data);
})
.error (function (data){
console.log ('Error: ' + data);
});
this.article = {};
};
this.resetArticle = function (){
this.article = {};
};
}]);
})();
Error
My main page doesn't show the list.
DOCS
Change your factory to service as you are using this factory return an object or primitive type not bind with this
app.services('articleFactory', ['$q', '$http', function ($q, $http){
this.getAllArticles = function (){
var deferred = $q.defer(),
httpPromise = $http.get ('/entries');
httpPromise.success (function (data){
deferred.resolve (data);
})
.error (function (err){
console.log (err);
});
return deferred.promise;
}
}]);
UPDATED ANSWER
Your controller should be like this:-
app.controller ('ArticleController', ['$http', 'articleFactory', function ($http, articleFactory){
this.article = {}; // Simple article.
this.list = []; // Article list.
articleFactory.getAllArticles()
.then (function (data){
this.list = data;
}, function (err){
console.error (err);
});
this.addArticle = function (){
$http.post ('/addEntry', this.article)
.success (function (data){
console.log (data);
})
.error (function (data){
console.log ('Error: ' + data);
});
this.article = {};
};
this.resetArticle = function (){
this.article = {};
};

Make a get request with restful api in angularjs

It's my first question here, sorry in advance if there's a discussion of what i'm going to ask, already. I'm new to angularjs and I'm pretty sure this is not a big problem, but I don't understand what I have to do. I'm working with API teech.io and I would like to get some experience to learn how to use them. My problem is this: make a GET request via http (each user has an app key and an app Id), for example to materials. The documentation of materials says this:
A GET to /materials/:id fetches the material object.
GET /materials/:id HTTP/1.1 Host: api.teech.io Teech-Application-Id:
[app ID] Teech-REST-API-Key: [API key]
<!DOCTYPE html>
<html>
<head>
<!-- INCLUDE REQUIRED THIRD PARTY LIBRARY JAVASCRIPT AND CSS -->
<script type="text/javascript" src="js/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-responsive.min.css">
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="teechpadController2.js"></script>
</head>
<body>
the app.js is this one
var app = angular.module('TeechTest',[]);
The teechpadController is this
teechpad.factory('$api', function($http) {
var defaults = {
method: null,
url: null,
headers: {
'Teech-REST-API-Key': api.teech.io.apikey,
'Teech-Application-Id': api.teech.io.appid.
}
};
var req = function(method, url, config) {
defaults.method = method;
defaults.url = 'http://api.teech.io' + url;
var h = angular.extend({}, defaults, config);
console.log(heart);
return $http(heart);
};
return {
get: function(url, config) {
return req('GET', url, config);
},
put: function(url, data, config) {
defaults['Content-Type'] = 'application/json';
defaults['data'] = data;
return req('PUT', url, config);
},
post: function(url, data, config) {
defaults['Content-Type'] = 'application/json';
defaults['data'] = data;
return req('POST', url, config);
},
delete: function(url, config) {
return req('DELETE', url, config);
}
}
});
What I understood till now is that teechpadcontroller re-define the PUT-POST-DELETE-GET methods. Now, How can I use, for example, get method in my controller? Or Should I create an other controller and then use $app there? Sorry again for everything, I'm very new here and in angularjs. Last but not least, I work with JSON object(I think it was clear already)
In your Controller (where you inject this factory) you could use this factory called $api.
The exposed functions to this $api is the four functions returned in the returncaluse:
return {
get: function(url, config) {
...
},
put: function(url, data, config) {
...
},
post: function(url, data, config) {
...
},
delete: function(url, config) {
...
}
}
so in your own controller you could use it something like this:
JavaScript
angular.module('myModule',['TechTest']).controller('myCtrl',function($api){
var customUrl = "/PATH/TO/ENDPOINT",
customConfig = {}; // might not be needed.
$api.get(customUrl, customConfig).success(function(data){
$scope.apiResult = data;
});
})
HTML (which needs to know about your controller per usual)
<!-- include scripts -->
<body ng-app="myModule">
<div ng-controller="myCtrl">
<div>{{apiResult}}</div>
</div>
</body>
I hope I did not missunderstood your quetion.
Now, How can I use, for example, get method in my controller?
You can use your '$api' inside any controller you define by adding it to the injectables of that controller through
var app = angular.module('TeechTest',[]).factory('$api', function($http){ ... });
var controller = app.controller('ctrl', ['$api', function($api){ ... }]);
and then call your 'get' method by going: $api.get( ... ); inside your controller.
Watch out, you've defined 'h' and 'heart' on two different lines, this might just be a typo but it might trip you up!
Your function call to $api.get( ... ); will return asynchronously and you will get the result inside either:
$api.get( ... ).success(function(response){ console.log(response); }); //success
$api.get( ... ).error(function(response){ console.log(response); }); //failure
This is a deferred callback - look into the promise API for more in depth details. You may also want to look into resetting the defaults object every time so you guarantee you're working with a clean object each function call.
Any incorrectness then say and I'll update my answer :)

How to set Angular JS $resource path (I'm getting 404s here)

I'm a noob to AngularJS and trying to set up a simple webapp in order to test, if the framework suites our needs. I've read the API reference and did the tutorial. Unfortunately the way path and locations are set and handled on $resource is not quite well explained there.
The problem I am facing is that I always get a 404 when I give $resource the relative path as described in the tutorial.
Here is my set up:
I have cloned the AngularJS phone cat app and threw away their phone stuff but made use of their structure to bring in my own logic. My index.html looks as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>testapp</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="testapp">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Testapp using AngularJS</a>
</div>
</div>
<div ng-view></div>
</body>
First trouble was that AngularJS doesn't seem to give any advice on how to oauth to a RESTful API, and their tutorial only gives a "dream scenario" of a server delivering hard-coded JSON, so I have hacked into their web-server.js in order to let the node.js server handle the API calls and return the resulting JSON. For oauth I did so successfully, yet for further API calls, it doesn't work.
Here's my hack:
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
/* Hack for RESTful API calls. */
var post = '';
var query = qs.parse(req.url);
if (req.method === 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function () {
post = JSON.parse(body);
console.log(post);
// method name is part of the parameters
// apiRequests is the module handling the API requests
apiRequests[post.method](post, res);
});
} else if (query.api === 'api') {
var query = qs.parse(queryString);
// method name is part of the parameters
// apiRequests is the module handling the API requests
apiRequests[query.method](queryString, res);
} else {
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
}
It's really just an ugly hack, but anyways. The login POST request is delegated to an oauth call and the api GET requests are delegated to the proper api request methods, the rest is handled the same way as web-server.js did before.
The trouble is, the handleRequest method is never called.
Here is my client side service code making the call:
return {
fetchCommunications : function ($scope) {
var parameters = {
'api': 'api',
'method': 'communications',
'bearer':userData["access_token"],
'chiffre':userData["chiffre"]
}
var resource = {
r : $resource('communications', {}, {
query: {method:'GET', params:parameters}
})
}
var d = resource.r.query();
console.log("Communications: " + d);
return d;
}
And this is the error message from the server console:
GET /app/communications?api=api&bearer=d6a348ea-0fe5-46fb-9b5e-13d3343c368d&chiffre=0000006F&method=communications Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
404 Not Found: /app/communications
This is exactly the path I'd expect to be called - but why is it 404?
I can avoid the 404 by configuring $resource like this:
var resource = {
r : $resource('index.html#/communications', {}, {
query: {method:'GET', params:parameters}
})
Which doesn't work either, since everything after the hash is omitted from the path. Besides, why would I need to have index.html within the path?
I have the feeling that I am missing something pretty obvious here and am therefore doing something pretty dumb. Anyone with any ideas? Is it something related to the configuration of node.js (never had this trouble before)?
Many thanks in advance!

Categories

Resources