AngularJS $http and filters - json

I have a JSON file, which contains:
{
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
Now I am reading this json file using $http, but I want to add a filter in below fashion:
Using window.location.pathname, I am reading path of the current page, suppose the current page is /about.aspx
Then I want to add a filter in $http response by which I want to read only aboutBg.
The code I wrote can retrieve all the values, but unable to filter that. Please help.

User this function where you receive the response.
function getPageBgClass(currentPage, responseData) {
if (responseData.hasOwnProperty(currentPage))
return responseData[currentPage]
else
return "none"
}
Here is how it should be used in your promise then function
function(response) {
var bg = getPageBgClass(window.location.pathname, response.data);
//Your code here ...
}

there is no direct method to get key using value from json.
you should make sure that there are no 2 keys having same value for below code to work
function swapJsonKeyValues(input) {
var one, output = {};
for (one in input) {
if (input.hasOwnProperty(one)) {
output[input[one]] = one;
}
}
return output;
}
var originaJSON = {
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
var invertedJSON = swapJsonKeyValues(originaJSON);
var samplepathname = "aboutBg";
var page = invertedJSON[samplepathname];
[function swapJsonKeyValues from https://stackoverflow.com/a/1970193/1006780 ]

Related

Why is async.map passing only the value of my JSON?

I have a function in node.js that looks like this:
exports.getAllFlights = function(getRequest) {
// this is the package from npm called "async"
async.map(clients, getFlight, function(err, results) {
getRequest(results);
});
}
The variable clients should be a JSON that looks like this:
{'"A4Q"': 'JZA8187', "'B7P"': 'DAL2098' }.
I expect that the map function will pass the individual indices of the array of the variable clients to getFlight. However, instead it passed the values of that each(ex: 'DAL2098', 'JZA8187' and so on).
Is this the expected functionality? Is there a function in async that will do what I want?
The signature of getFlight is getFlight(identifier, callback). Identifier is what is currently messed up. It returns callback(null, rtn). Null reprsents the nonexistence of an error, rtn represents the JSON that my function produces.
Yes, that's the expected result. The documentation is not very clear but all iterating functions of async.js pass the values of the iterable, not the keys. There is the eachOf series of functions that pass both key and value. For example:
async.eachOf(clients, function (value, key, callback) {
// process each client here
});
Unfortunately there is no mapOf.
If you don't mind not doing things in parallel you can use eachOfSeries:
var results = [];
async.eachOfSeries(clients, function (value, key, callback) {
// do what getFlight needs to do and append to results array
}, function(err) {
getRequest(results);
});
Another (IMHO better) workaround is to use proper arrays:
var clients = [{'A4Q': 'JZA8187'},{'B7P': 'DAL2098'}];
Then use your original logic. However, I'd prefer to use a structure like the following:
var clients = [
{key: 'A4Q', val: 'JZA8187'},
{key: 'B7P', val: 'DAL2098'}
];
First create a custom event. Attach a listener for return data. then process it.
var EventEmitter = require('events');
var myEmitter = new EventEmitter();
myEmitter.emit('clients_data',{'"A4Q"': 'JZA8187'}); //emit your event where ever
myEmitter.on('clients_data', (obj) => {
if (typeof obj !=='undefined') {
if (obj.contructor === Object && Object.keys(obj).lenth == 0) {
console.log('empty');
} else {
for(var key in obj) {
var value = obj[key];
//do what you want here
}
}
}
});
Well, you need to format your clients object properly before you can use it with async.map(). Lodash _.map() can help you:
var client_list = _.map(clients, function(value, key) {
var item = {};
item[key] = value;
return item;
});
After that, you will have an array like:
[ { A4Q: 'JZA8187' }, { B7P: 'DAL2098' } ]
Then, you can use async.map():
exports.getAllFlights = function(getRequest) {
async.map(client_list, getFlight, function(err, results) {
getRequest(results);
});
};

Calling the JSON correctly

I have a JSON array fetched from the service to the controller. I'm able to display the JSON array in the console. But when a specific item from the JSON, is called it display's undefined. So how do I call it correctly so that I can use it in my view.
Controller:
$scope.onViewLoaded = function() {
callingService.getdata($scope.datafetched);
}
$scope.datafetched = function(response) {
debugger;
if (response) {
$rootScope.mainData = response;
$scope.localizeddataTypes = getLocalizedCollection($scope.mainData);
}
}
$scope.editFunction = function(key) {
console.log($scope.mainData);
debugger;
console.log($scope.mainData.keyValue);
}
Here console.log($scope.mainData); display's the JSON array but console.log($scope.mainData.keyValue); is displayed as undefined. And my JSON looks like
{
keyValue: "1234DEF56",
animals: {
name:"dog",
color:"brown"
},
birds:{
name:"canary",
color:"yellow"
}
}
So, how do I overcome this problem and why do I get it as Undefined.
Just a curiosity stuff. I feel that the content in that variable is stored in string format and not JSON or JavaScript Object. Try this, and see if that works?
$scope.mainData = JSON.parse($scope.mainData);
console.log($scope.mainData.keyValue);

How to modify JSON Object retrived from MongoDB?

So I am making a rest call to get this JSON Object:
{
"_id":"57a0811276e75ba815d248b0",
"gName":"demo-layout",
"gType":"Content",
"wsId":"57a036c376e75ba815d248ac",
"desc":"Demo-Layout for rapidpage",
"createdDate":"2016-08-02T11:16:34.223Z",
"__v":0
}
Now I want to add an array to this object ,something like this:
{
"_id":"57a0811276e75ba815d248b0",
"gName":"demo-layout",
"gType":"Content",
"wsId":"57a036c376e75ba815d248ac",
"desc":"Demo-Layout for rapidpage",
"createdDate":"2016-08-02T11:16:34.223Z",
"blocks":[], //should be added at runtime
"__v":0
}
So I tried following:
dbPage:any={};
ngOnInit(){
let pageId:string="57a0811276e75ba815d248b0";
this._pagesService.getPageById(pageId).subscribe((Page)=>{
this.dbPage=rapidPage;
console.log(this.dbPage); //this prints the object as shown above
});
this.dbPage.blocks=[];
this.dbPage.blocks.push(block1);
}
But its not modifying the current object,instead its creating new Object as :
{blocks: Array[]}
any inputs?
That's because you're not assigning it in the subscribe call. Due to the async nature of HTTP requests in JavaScript, the code below the subscribe call will be executed before the callback inside the subscribe call.
You can easily fix this by moving the code inside the callback:
dbPage: any = {};
ngOnInit(){
let pageId: string = "57a0811276e75ba815d248b0";
this._pagesService.getPageById(pageId).subscribe((rapidPage) => {
this.dbPage = rapidPage;
console.log(this.dbPage); //this prints the object as shown above
this.dbPage.blocks = [];
this.dbPage.blocks.push(block1);
});
}

Unable to send data in response to the view in nodejs

I am trying to create a simple web application which fires a http.request call, get the data and display it over to the html(ejs here). I am able to fire the request, get the data, massage it etc.. but unable to pass it to the view. Sample code is as below:
var searchData = [];
router.post('/',requesthandler);
function requesthandler(req,res){
var options = {
host: url,
port: 9999,
path: qstring,
method: 'GET'
};
var reqget = http.request(options,responsehandler);
reqget.end();
console.log('Rendering now:............................ ');
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
function responsehandler(ress) {
console.log('STATUS: ' + ress.statusCode);
ress.on('data', function (chunk) {
output += chunk;
console.log('BODY: ' );
});
/* reqget.write(output); */
ress.on('end',parseresponse);
}
function parseresponse(){
var data = JSON.parse(output);
console.log(data.responseHeader);
// populate searchData here from data object
searchData.push({//some data});
}
function errorhandler(e) {
console.error(e);
}
module.exports = router;
Problem is I a unable to pass the objeect searchData to the view via res.render();
'Rendering now: ...........' gets executed before execution starts in parseresponse() and so the page is displayed without the data which seems to be in conjuction with using callbacks, So how can I pass the data object to the view once the searchData is loaded in parseresponse().
PS: I am able to print all console statements
define res variable globally:
var res;
function requesthandler(req,resObj){
res = resObj;//set it to the resObj
}
wrap res.render inside a function like this:
function renderPage(){
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
then in parseresponse function do this:
function parseresponse(){
var data = JSON.parse(output);
searchData.push({some data});
renderPage();
}
Hope this solves your problem.

Knockout: Mapping/binding JSON

I'm new to knockout. I'm trying to bind the json returned from ajax call but it isn't happening.
<script type="text/javascript">
var ServerData;
$(document).ready(function () {
ko.setTemplateEngine(new ko.nativeTemplateEngine);
var oViewModel = new CompanyModel();
oViewModel.Newitem(new Company("","","","","","","","","","","","","","",""));
ko.applyBindings(oViewModel);
BasicDatatable('#TableCompany');
});
function CompanyModel() {
var self = this;
self.CompanyList = ko.observable();
$.getJSON("getallcompanies", function (response) {
ServerData = ko.mapping.fromJSON(response);
self.CompanyList(ServerData);
});
}
In response I've the required data. But in ServerData I'm getting the following instead of the list.
function b() { if (0 < arguments.length) { if (!b.equalityComparer || !b.equalityComparer(d, arguments[0])) b.H(), d = arguments[0], b.G(); return this } r.T.Ha(b); return d }
Can You please let me know what's going wrong?
You should use ko.mapping.fromJS to bind JSON that comes from server.
Also, you don't need to define self.CompanyList = ko.observable(); and bind set value to that property in self.CompanyList(ServerData);.
It's all done by ko.mapping.fromJS. From Knockout Mapping documentation:
All properties of an object are converted into an observable. If an
update would change the value, it will update the observable.
Arrays are converted into observable arrays. If an update would
change the number of items, it will perform the appropriate
add/remove actions. It will also try to keep the order the same as
the original JavaScript array.
Try to change code like this:
function CompanyModel() {
var self = this;
$.getJSON("getallcompanies", function (response) {
ko.mapping.fromJSON(response, {}, self);
});
}