Passing data from server to angular - javascript

Sorry, I'm a newbie at this
Let's say i have the following in node express
router.get('/:name', function(req, res, next) {
res.render("test", {test:req.test});
});
how to do I get the angular to pick up the test variable?
i tried doing in the html page
<div ng-controller='UserCtrl'>{{ data }}</div>
<script>
var test=!{JSON.stringify(test)};
</script>
then on the angular page
productApp.controller('UserCtrl',function UserCtrl($scope){
$scope.data=test;
});
the req.test looks like this
[
{
name: 'test'
}
]
the 'data' shows empty everytime.
thank you for your help

If you want Angular to talk to a server, the most common way is through an AJAX request. Angular has a whole service to help you with this communication.
https://docs.angularjs.org/api/ng/service/$http
The first example pretty much does exactly what you are looking for:
$http({
method: 'GET',
url: '/testName'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
It uses promises for the response. Just add your actions in the proper call back function and away you go.

You will need to use ajax call from an angular script or service in order to get the express js backend response.
You can create a service like below -
productApp.service("API", function($http){
this.callAPI = function(name){
return $http({
url : "localhost:3000/"+name,
data : "", // pass data if any here
method: "get"
});
};
});
Then you will need inject this service in your controller and call like below -
productApp.controller('UserCtrl',function UserCtrl($scope, API){
//$scope.data=test;
// call service api here
API.callAPI("some name").then(function(response){
$scope.data = response;
}, function(){
// error goes here
});
});
Also, you can change your express js app to send the JSON data as follows -
res.json({...}); // instead of res.render(..);

Inside your express res.json() is, in my opinion, the best option you have since any object passed to it will be converted to JSON other way you can do it like you've done but render is more suited to html where you have to render a nice little view for the client or there is some sort of manipulation involved before sending the JSON on the wire or the json is too big and you don't want to make you router file dirty and rather delegate that to a view file.. else res.json() is a very neat way to do it.
Modify your controller code like:
productApp.controller('UserCtrl',['$scope', '$http' , function($scope, $http){
$http.get('/test').then(
function(response){
$scope.data = test;
},
function(err){
console.error(err);
}); //'/test' <- this is the url;
//$scope.data=test;
}]);
and remove this from your code
<script>
var test=!{JSON.stringify(test)};
</script>

I would recommend doing an $http service call to receive this variable BUT if you truly want this variable/data rendered directly in to the page and available in the controller, you should consider doing the following:
In the rendered/returned HTML:
<head>
...
<script>
angular.module('myAppConfig', [])
.value('MyTestConfig', !{JSON.stringify(test)});
</script>
</head>
<body ng-app="myApp">
...
<div ng-controller='UserCtrl'>{{ data }}</div>
...
</body>
This will setup an injectable configuration value called 'MyTestConfig'. Ideally, this should be part of a bigger object or service so you could do things like Config.apiPath or Config.getStaticResource('my-resource.png')
Your controller will now look like this:
productApp.controller('UserCtrl', function UserCtrl($scope, MyTestConfig){
$scope.data = MyTestConfig;
});
and your original modal definition will look something like this:
angular.module('myApp', ['myAppConfig']);
You may need to shuffle around where the script tag is depending on how you have configured your views. This will also only work before injection has been finalized, aka, this will not work for partials.

Related

$http get returns not found,while the direct request works good

I am trying to use one webAPI coded in ASP.net but when I try to get data from that API using angular $http.get at the browser console I get GET <--URL--> Not found When I try to make requests to the same URL directly it works fine and returns data to me. I tried to add .json mimetype at Web.config in the ASP project but still same result.
The working url is: https://adaba.azurewebsites.net/api/flights/searchairports?name=london - note that it's a GET request with a required parameter so you need to pass a parameter to get something.
Here you can execute directly the api request from this Codepen: http://codepen.io/albpower/pen/mVgyNP
JS file:
var app = angular.module("APP",[]);
app.controller("appCtrl",function($http,$scope){
$scope.calculate = function(){
$http.get('http://adaba.azurewebsites.net/api/flights/searchairports',{
name: $scope.input
}).then(function (resp) {
console.log(resp);
$scope.response = resp;
});
}
})
HTML file:
<div ng-app="APP" ng-controller="appCtrl">
<input type="text" placeholder="amount" ng-model="input"><br><br>
<button ng-click="calculate()">Calculate</button>
<pre>
{{response | json}}
</pre>
</div>
You issue is:
you are not setting the parameters for the request correctly, you need to do this with the params property
The code should be:
$http.get('https://adaba.azurewebsites.net/api/flights/searchairports',{
params: {name: $scope.input}
}).then(function (resp) {
See here: http://codepen.io/anon/pen/OMGpqX
Oh, and please use https://

Basic REST calls to WordPress V2 API with Angular.js

I'm trying to get a basic query going with the new V2 API and Angular in WordPress 4.4.1. Perhaps someone can help me understand why the URL, /wp-json/wp/v2/posts, gives a JSON response with a 404.
Browsing to that URL gives me JSON like this:
{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
And here is the JavaScript I'm using to make that .GET
var base = 'http://localhost:8888/recruitler';
var posts = '/wp-json/wp/v2/posts';
var user = '/wp-json/wp/v2/users/'; // append user id
var s = '/wp-json/wp/v2/posts?filter[s]='; // append search term
// basic HTTP call with Angular
var app = angular.module('app', ['ngRoute'])
app.factory('myService', function($http) {
var myService = {
async: function() {
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http.get( base+posts ).then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return myService;
});
app.controller('MainCtrl', function( myService, $scope ) {
// Call the async method and then do stuff with what is returned inside our own then function
myService.async().then(function(d) {
$scope.data = d;
});
});
UPDATE:
This must be a local environment issue. Live websites work just fine. I've tested and this issue persists on all my local WAMP and MAMP dev sites. Restarting the server and or checking this answer got it working.
the factory looks right, according to the rest-api docs you need pretty permalinks plugin as well in order to rest-api plugin use custom url rewrites https://wordpress.org/plugins/rest-api/installation/

Parsing a JSONP file in AngularJS

I'm new to Angular and also relatively new to the JSONP format. In my code, I set up a factory to read in the JSONP file - and I get back the data variable as the JSONP data properly
$http.get('someJSONFile').success(function(data){
console.log(data);
});
The console log gives me back the following:
states([{"code":"AL","name":"Alabama"},{"code":"AK","name":"Alaska"},{"code":"AZ","name":"Arizona"},{"code":"AR","name":"Arkansas"},{"code":"CA","name":"California"},{"code":"CO","name":"Colorado"},{"code":"CT","name":"Connecticut"},{"code":"DE","name":"Delaware"}])
So - I'm stuck on what to do now. I have a data object that contains a function. I need to parse out the JSON from this function - but not sure how to do it.
I have read in other places that I need to declare a function somewhere in my controller or factory called
function states(results)
{
// what is in results should be the JSON data I crave
}
But even if I do that, I don't think it ever executes - so I am not sure what I should do at that point to get the JSON data into an object that I can use.
The full file I am trying to parse is http://massachusettswebdesigns.com/states.json
Any help is appreciated!
Angular $http service provides a method to consume JSONP endpoints. In your case this should work:
$http.jsonp('someJSONFile').then(function(data) {
console.log(data)
});
Behind the scene, Angular will create a globally accessible function that will receive data, parse and pass further, so you don't need to worry about creating functions yourself.
What looks like your trying to do is standard JSON not JSONP, JSONP will require a callback and is only required if getting data from a different domain, ie a API service
Also the console log output you give is not valid JSON.
//init app
var app = angular.module('MyApp',[]);
//setup a factory for the data handling
app.factory("Data",function($http){
return {
getData:function(type){
return $http.get(type).
then(function(result) {
return result.data;
});
}
}
});
//in a controller 'call' the factory for the data
app.controller('main', function main($scope, Data) {
//other stuff
Data.getData('someJSONFile').then(function (data) {
$scope.jsonData = JSON.parse(data);
});
//other stuff
});
So my error was a stupid one. The JSON file was giving me the name of a custom callback I had to define. Once I did this, all worked. . . . here's the code
angular.module('locationApp')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.states = [];
$scope.cities = [];
// Function for the States callback on the JSON files provided
window.states = function (data)
{
$scope.states = data;
};
// Get the State JSON file.
$http.jsonp('http://locationinc-mapping-demo.herokuapp.com/states.json');
}]) // end of MainCtrl

error when reading json file using angular resource

I'm trying to use angular ngResource module to fetch data from json file but I get an error 404 on the console - the URL is being concatenated with code following the call to get function.
Here is the error:
localhost prefix/test_data/data.json/function%20(data)%20%7B%20%20%20%20%20%20%20%20%20%20%20%20console.log(data);%20%20%20%20%20%20%20%20%7D
here is the code I'm using:
the json service -
angular.module('jsonServices',['ngResource']).factory('JsonService',
function ($resource) {
return $resource('/test_data/data.json');
});
the controller using the service:
angular.module('myApp.controllers')
.controller('mainController', function ($scope, JsonService) {
JsonService.get(function (data) {
console.log(data);
});
});
the app js that starts it all:
angular.module('myApp',['myApp.controllers','jsonServices','ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('home',{
url:'/home',
template:'some template path goes here',
controller:'mainController'
};
});
As you can see the "function(data)" is being added to the url as a string. one more thing is when I try to access the json file browsing to its location I can see the content of the json file OK.
Does anyone got this problem before and find a way to solve it? Is there something I'm doing wrong or missing here?
Thanks,
Eran
Found the problem, it seems that I used a bower package call ng-resource instead of angular-resource.

AJAX data transfer between angularjs front-end and nodejs back-end

FYI: There is main question on the bottom if you ever feel like my post is too long ;)
Im trying to build my first angularjs app and now Im stuck with collecting data via ajax from nodejs (express) server.
In front-end Im loading templates with angularjs routers and ng-view. In every route i have template and specific controller (this should be pretty basic thing right?).
OK here comes the wall... I was thinking to put $http.get() to load right stuff for the template from the nodejs server in the controller. With GET I could send variables like this.
$http.get('http://.../API', { params: { twitterData : true, needed : "data2" } } )
.success( function(result) {
// pass result to template.
});
And then on the server side get params like this.
router.get('/', function(req, res) {
this.params = req.query;
// here run every function and collect it to one object
// then return it for front-end ajax call.
res.send(JSON.stringify(collectedDataObj));
}
collectedDataObj could look something like this:
{ twitterData :
{ thisIs:twitterObject },
blog : {title: "...", content: "..." }
}
Collecting data would be by nested callbacks like introduced here http://book.mixu.net/node/ch7.html
So is this "collecting all data in back-end" best way to get data or should I send many ajax calls to collect data for one angular view?
Meaning one $http.get() for getting titter object and one for blog content etc.
And of course if you know some pass me links for good tutos/examples.
IMO, whenever possible it's best to get everything you can in one request. Trips back and forth to the server get pretty expensive.

Categories