How can I access value in json in AngularJS - javascript

I am using nodeJS so the server will send the following json object to controller by doing:
data = {
"question": "theQuestion",
"answer": "theAnswer"
};
res.json(data);
Then in the controller, I want to manipulate the variable like:
data = QA.get();
$scope.q = data[question] + "Some additional info here";
QA is the service defined as:
angular.module('questionServices', ['ngResource'])
.factory('QA', function ($resource) {
return $resource('/qa');
});
However, the error message always tells me that data[question] is undefined. What is the right way to access the value? I have tried data.question. It doesn't work either.
I know I can simply show the json values by using ng-repeat in html but I want to be more flexible managing the values.

Seems you QA function you use $http or $resource to get the ajax response.
If you return $http.get/$http.post in you QA service, you can use this code to handle the json response:
QA.get().success(function(data){
console.log(data);
console.log(data.answer);
}).error(functoin(data){
//handle error here.
});
If you use $resource in your QA service, then you can use this code to handle that:
QA.get().$promise.then(function(data){
console.log(data);
console.log(data.answer);
}).then(function(error){
//handler error here.
});
Here is $http document.
Here is $resource document.
P.S you need to understand in ajax, javascript handle the request in async. That means when
exec these code:
$scope.data = QA.get()
console.log($scope.data); // QA.get() send a http request. Now data is still promise object.
you cannot get this response immediately. So if you try to log the data, or use console.log(data.answer) to get data.answer. you will get undefined
However in you html view. You can get the data with {{data|json}} . This is because angular will $watch your data. And once data($resource promise object) is change(means http request is finished), Angular will render your view automatically.
That's why in your view you can get data.answer. But in your controller, you cannot.

$scope.data = QA.get();
console.log(data);
or in your template: {{data | json}}
This will give you a hint

Related

request.body.email is undefined node js server side using http.get

I have a problem where request.body.email returns me undefined.
I wrote this code on my controller on my client side:
wish.controller('wishCtrl',['$scope','$http','$cookies',function($scope,$http,$cookies) {
var user={};
user.email = $cookies.get('cookieEmail');
console.log(user.email);
$http.get("http://localhost:3000/wishlist",user).success(function(data){
$scope.wishController = data;
console.log(data);
});
}]);
here I see - user.email ok so there is no problem here.
on my controller on my server side I wrote:
exports.getData = function(request, response) {
userEmail = request.body.email;
console.log(userEmail);
}
which writes me back undefined.
to call this function I have on my server.js (on the server side)
app.get('/wishlist',wish.getData);
any idea how to fix it?
You are making a GET request. There is no request body in a GET request.
If you want to read query string data then parse request.url.
The Angular documentation for get says that the last argument must be a configuration object. So it looks like you aren't even managing to put your data in the URL either. Pass a configuration too.
$http.get("http://localhost:3000/wishlist",user, {})
because i't get function have to pass the email on the client side this way:
$http.get("http://localhost:3000/wishlist/"+user.email)
and the path of the sever should recognize it that way:
app.get('/wishlist/:email',wish.getData);
and int the controller that way:
userEmail = request.params.email;
console.log(userEmail);

AngularJS: Error in resource configuration for action `query`. Expected response to contain an object but got an array

I am trying to call a REST service using Angular 1.3 but keep getting an "Error: error:badcfg
Response does not match configured parameter".
I suspect it is in my controller where I call the $scope.data. I believe .data is correct but it is throwing this error.
Here is my service, including a test REST call:
var pfcServices = angular.module('pfcServices', ['ngResource'])
pfcServices.factory('pfcArticles', ['$resource',
function($resource){
return $resource('https://myrestcall.com/data, {}, {
query: {method:'GET'}
});
}]);
Here is my controller:
var pfcControllers = angular.module('pfcControllers', []);
pfcControllers.controller('pfcCtrl', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {
$scope.data = pfcArticles.query();
}]);
Within IE, I get a CORS message of: XMLHttpRequest for https://pfc.azure-mobile.net/tables/articles required Cross Origin Resource Sharing (CORS). This does not occur within Chrome.
However, I am not sure if this is related, or just a bad call on my part. I have added my test site to the CORS in Azure Mobile Webservices where I am hosting the test REST call.
I am newer to Angular, so I am leaning towards a bad call on my part.
I am not sure why have set query properties on the resource. Either remove the configuration for query
return $resource('https://pfc.azure-mobile.net/tables/articles', {});
or set isArray true on the query configuration.
return $resource('https://pfc.azure-mobile.net/tables/articles', {}, {
query: {method:'GET',isArray:true}
});
The error is coming because Angular is not able to deserialize your response as it expects an object but the response from the call is an array.
The query method on $resource already has this flag set, but since you are redefining the query configurations this error is occurring. Do check the $resource documentation.

Use angular to call multiple actions from Node.js

Please help, I'm unflushed in programming  . I created a route router.get('/statistics', routesCtrl.statistics) for a page where I want to display some statistics in some charts, using Angular.
I realized that I need to send some query results like, how many registrations are in db, how many of them have "this property", how many of them have “those properties” and so on, being something new for me. Until now in responses of the routes I sent only one statistic from the above list.
How should I send this info to Angular, should I create a literal object containing those statistics, packing them in the response and send it to the Angular? Or to send the entire json from db and parse it in Angular, but it seems to be a wrong idea also because I can't use then mongoose queries from Angular if it's true :) .
I don’t have any other idea and there probably are more professional ways. Thank you!
It is very simple, whenever you need data from server side, which is node.js in your case or anything it may be like PHP, asp.nrt etc you have to send http requests to server using angular $http (GET/POST) and along with required parameters as a json object or query string. At server end write some rest service type stuff to handle this and make use of send parmeters at server to query mongo and than pass collected data as a json object back to angular end. At angular you can parse this JSON, and angular have also scope to use JSON/Array directly in view using attribute ng-repeat and so on depends on your exact requirement.
Request in angular.js
var sendConfig = {
method : "POST",
url: "YOUR_URL",
data: {action : 'Test_Service'},
headers : {}
};
$http(sendConfig).success(function(response) {
console.log(response);
}).error(function(error) {
console.log(error);
});
Response In node.js
var server = http.createServer(function(req,res){
var webservice_actions_instance = new webservice_actions(req, res);
var service_response = {data : 'RESPONSE_HERE_AFTER_CERTAIN_ALGOS'};
res.writeHead(200, {'Content-Type': 'text/html',"Access-Control-Allow-Origin": "*","Access-Control-Allow-Headers":" X-Requested-With"});
res.write('Response Data '+ service_response);
res.end();
}).listen( 8080 );

Sailsjs: Setting response method based on request parameter

So I have been working on a SPA project using Sailsjs. The problem is:
When the first page loads, I use res.view or res.render in my controller. But, for subsequent requests, I dont want to use res.view or res.render, rather I'd like to use res.json.
Right now, I use the method:
return req.param('json') ? res.json(myObj) : res.view('layout', myObj);
This works, but I was looking for a more generic and abstract method in which my controller itself would know (on the basis of req.param('json')) whether to use res.view or res.json without me having to tell it explicitly.
Any help ?
This is what res.ok() is for.
In the controller action below, res.ok will either display the myAction.ejs using data as the view locals, or respond with data as JSON, depending on how the request came in (i.e. via AJAX, sockets or a regular browser request):
module.exports = {
myAction: function(req, res) {
var data = {someKey: "someVal"};
return res.ok(data);
}
}
Internally, the ok response uses req.wantsJSON to determine what to do; it checks headers, looks for an xhr object and generally does its best to guess your intent. req.wantsJSON is available for all requests (as is req.isSocket), so you can use them yourself as needed.
So after a bit of tinkering, I resolved this using a service.
I wrote a service (in GlobalUtils.js):
render: function (req, res, obj) {
if(req.param('json')) {
return res.json(obj);
}
else {
return res.view('layout', obj);
}
}
And I use this service in my controllers, like so:
return GlobalUtils.render(req, res, myObj);
But still, looking for a better method.

AngularJS unwanted Behavior when reloading page

I'm developing an Angular application with the MEAN stack, so suppose you got an express route that make a query to the databse, the results are sent in the response:
app.get('/api', function(req, res){
Todo.find({}, "", function(err,todos){
if (err)
res.send(err);
res.json(todos);
});
});
In the client-side:
Controller :
...
Todo.get().success(function(data){ //i got the service with the $http call
$scope.todos = data;
});
When I go to localhost:8080/#/api, I can see my partial and the data I requested.
The problem that I'm having is that if I omit the hashtag, i don't see the partial, I only see the response data in JSON format.
I also tried to use html5 mode, but if I reload I got the same behavior.
Any ideas on how can I avoid this behavior??
Anything after the # isn't sent to the server. So when you go to localhost:8080/#/api, expressjs just sees a request to / and returns the AngularJS template. AngularJS then routes the browser page using the /#/api, which called the Todo.get() and (I assume) makes a call to localhost:8080/api, returning the data from the DB.
That's why you only get the data when you omit the hash and when you use html5 mode.
I would suggest changing your API call to:
/api/todos - return data from the db
And change your AngularJS route to just use:
/todos - show the partial and data requested

Categories

Resources