How to call function recursively - angularjs

I'm trying to call my mapper function recursively but getting the error not defined: 'ReferenceError: mapper is not defined at Object.mapper'
Could use some guidance on how to call the function recursively in this particular situation.
angular.module('dvb.transferObjects').value('MappedTransferObject', function(obj1) {
'use strict';
return {
mapper: function(obj2) {
for (var p in obj1) {
if (typeof obj1[p] === 'object') {
mapper(obj1[p], obj2[p]);
} else {
if(obj2.hasOwnProperty(p)) {
obj1[p] = obj2[p];
}
}
}
return obj1;
}
};
});
I'm injecting this value in my controller as MTO and using it as follows:
var mto = new MTO(appState.getTemplateObject());
var mappedObject = mto.mapper($scope.dvModel);

If you add a name to your anonymous function you can call it inside itself like so:
angular.module('dvb.transferObjects').value('MappedTransferObject', function (obj1) {
'use strict';
return {
mapper: function mapper(obj2) {
for (var p in obj1) {
if (typeof obj1[p] === 'object') {
mapper(obj1[p], obj2[p]);
} else {
if (obj2.hasOwnProperty(p)) {
obj1[p] = obj2[p];
}
}
}
return obj1;
}
};
});
The reason you can not use mapper in your example is due to the mapper being scoped to the object itself. This means the only way to access the function would be to call it through the object, which you can't do without saving off a reference to the object before returning it:
angular.module('dvb.transferObjects').value('MappedTransferObject', function (obj1) {
'use strict';
var mapper = {
mapper: function (obj2) {
for (var p in obj1) {
if (typeof obj1[p] === 'object') {
mapper.mapper(obj1[p], obj2[p]);
} else {
if (obj2.hasOwnProperty(p)) {
obj1[p] = obj2[p];
}
}
}
return obj1;
}
};
return mapper;
});

Related

Angularsjs cannot find service function

My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
angular.module('BrandService', [])
.service('BrandService', function ($filter, DataService) {
var productDb;
var products;
return {
filterProducts(brands, priceRange) {
var filteredProducts = [];
var brandProducts = [];
var priceProducts = [];
var productsArray = [];
var brandChecked = false;
var priceChecked = false;
angular.forEach(brands, function (brand) {
if (brand.checked) {
brandChecked = true;
angular.extend(brandProducts,
$filter('filter')(productDb, { 'brand': brand.name }));
}
if (brandChecked) {
productsArray.push(brandProducts);
console.log('brandProducts = ', brandProducts)
}
});
angular.forEach(priceRange, function (price) {
if (price.checked) {
priceChecked = true;
let filteredProductDb = productDb.filter((prod) => {
return (prod.price >= price.low && prod.price <= price.high);
});
angular.extend(priceProducts, filteredProductDb);
}
});
if (priceChecked) {
productsArray.push(priceProducts);
// console.log('priceProducts = ', priceProducts)
}
if (!brandChecked && !priceChecked) {
filteredProducts = products;
} else {
if (productsArray.length > 1) {
filteredProducts = findIntersection(productsArray);
} else {
filteredProducts = productsArray[0];
}
}
return filteredProducts;
},
findIntersection(productsArray) {
console.log('findIntersection called')
var filteredProducts = [];
var filteredSet = new Set();
for(var i=0; i < productsArray.length - 1; i++) {
var products1 = productsArray[i];
var products2 = productsArray[i+1];
angular.forEach(products1, function(product1) {
angular.forEach(products2, function(product2) {
if(product1._id == product2._id) {
filteredSet.add(product1);
}
});
});
}
filteredProducts = Array.from(filteredSet);
return filteredProducts;
}
}
})
My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
You are returning a javascript object with properties. You are not defining global functions.
You need to store the service returned before :
var service = { findProducts: ... , findIntersection: ... };
return service;
And instead of calling findIntersection, call service.findIntersection.
You have to make a reference to local object.
Simply change this: filteredProducts = findIntersection(productsArray);
to this: filteredProducts = this.findIntersection(productsArray);

AngularJS Service as Singleton to Storage files

I have I'm trying to write an AngularJS service which should work as singleton in storage files. There should be two methods:
for writing files by key getFilesForTabId
for getting saved files from setFilesForTabId
I'm trying to write something like this:
app.factory('fileStorage', ['LogService', function (LogService) {
var fileStorage = {
this.files = {};
this.getFilesForTabId = function (key) {
return this.files[key];
};
this.setFilesForTabId = function (key, files) {
this.files[key] = files;
return true;
}
}
return fileStorage;
}]);
But this code is bad. There are errors when I'm trying using it. How could I write it? I'd grateful for help
Now I have a problem with getFilesForTabId function. I'm trying to run this function with undefined files[key] object.
My actual service code is:
app.factory('fileStorage', ['LogService', function (LogService) {
var fileStorage = {
files: {},
setFilesForTabId: function(key,files){
this.files[key] = files;
return true;
},
getFilesForTabId: function (key) {
if(typeof(files[key]) === undefined) {
return [];
}
else{
return this.files[key];
}
}
}
return fileStorage;
}]);
Below I show error from browswer:
You can't use = in {} object.
var fileStorage =
{
files: {},
getFilesForTabId: function (key) {
return this.files[key];
},
setFilesForTabId: function (key, files) {
this.files[key] = files;
return true;
}
};
you are trying to initialize fileStorage as an object but are writing it like a function instead. you need to use Object Initializer Syntax.
Try this instead:
app.factory('fileStorage', ['LogService', function(LogService) {
var fileStorage = {
files: {},
getFilesForTabId: function(key) {
return this.files[key];
},
setFilesForTabId: function(key, files) {
this.files[key] = files;
return true;
},
};
return fileStorage;
}]);

Parsing JSON (accessing $Ref) Angular

I have a problem on parsing of my JSON data. On my object 2, I would have the "t_quartier" while the value is just a reference that points to the object 1.
How can I get this value if I'm on my item 2?
thank you a lot
You could use this:
angular.module('app').service('commonService', commonService);
function commonService() {
//DFS for fixing JSON references
var elements = {}
this.fixReferences = function (json) {
var tree = json;
for (var x in tree) {
if ((typeof (tree[x]) === 'object') && (tree[x] !== null)) {
var result = dfsVisit(tree[x]);
tree[x] = result;
}
}
return tree;
}
function dfsVisit(tree) {
for (var x in tree) {
if ((typeof (tree[x]) === 'object') && (tree[x] !== null)) {
var result = dfsVisit(tree[x]);
tree[x] = result;
}
}
if (tree["$ref"] !== undefined) {
var ref = tree.$ref;
if (elements[ref] !== undefined) {
tree = elements[ref];
}
} else if (tree["$id"] !== undefined) {
var element = tree;
elements[element.$id] = element;
}
return tree;
}
}
You could define that function wherever you want but a service would be a clean way.
For using it:
angular.module('app').factory('yourService', yourService);
/*#ngInject*/
function yourService($http, commonService) {
var service = {
get: get
};
return service;
function get() {
return $http.get('Your url').then(function (response) {
var fixedData = commonService.fixReferences(response.data);
return fixedData;
});
}
}

How to reuse functions in an AngularJS factory?

I have an AngularJS factory for some common local storage manipulation. It's a common set of functions against different variables. I am constructing it so that the functions are repeated depending on which variable needs to be manipulated. Likely not an elegant way to go about this so open to options.
The factory looks as follows. Is there a way to reuse functions depending on the variable without so much code bloat?
angular.module('app.datastore', [])
.factory('DataStore', function() {
var venue = angular.fromJson(window.localStorage['venue'] || '[]');
var prize = angular.fromJson(window.localStorage['prize'] || '[]');
function persist_venue() {
window.localStorage['venue'] = angular.toJson(venue);
}
return {
list_venue: function () {
return venue;
},
get_venue: function(venueId) {
for (var i=0; i<venue.length; i++) {
if (venue[i].id === venueId) {
return venue[i];
}
}
return undefined;
},
create_venue: function(venueItem) {
venue.push(venueItem);
persist_venue();
},
list_prize: function () {
return prize;
},
get_prize: function(prizeId) {
for (var i=0; i<prize.length; i++) {
if (prize[i].id === prizeId) {
return prize[i];
}
}
return undefined;
},
create_prize: function(prizeItem) {
venue.push(prizeIem);
persist_prize();
}
};
});
My approach is to return in the factory a function which will return a store of a type (venue, prize, ...)
angular.module('app.datastore', [])
.factory('DataStore', function () {
var getStoreFunction = function (storeName) {
var store = angular.fromJson(window.localStorage[storeName] || '[]');
function persist() {
window.localStorage[storeName] = angular.toJson(store);
};
return {
list: function () {
return store;
},
getItem: function (id) {
return store.find(function (elem) {
return elem.id === id;
});
},
createItem: function (item) {
store.push(item);
persist(store);
}
}
};
return { getStore : getStoreFunction };
});
you can create unlimited store by using
var venueStore = DataStore.getStore('venue');
//use of your store
venueStore.createItem({
id : venueStore.list().length + 1,
name : 'myVenue' + venueStore.list().length + 1
});
$scope.venues = venueStore.list();
you can create a factory per type if you want or use it directly in your controller as in this example : https://jsfiddle.net/royto/cgxfmv4q/
i dont know if your familiar with John Papa's angular style guide but you really should take a look it might help you with a lot of design questions.
https://github.com/johnpapa/angular-styleguide
anyway - i would recommend you use this approach -
angular.module('app.datastore', [])
.factory('DataStore', function () {
var venue = angular.fromJson(window.localStorage['venue'] || '[]');
var prize = angular.fromJson(window.localStorage['prize'] || '[]');
return {
list_venue: list_venue,
persist_venue: persist_venue,
get_venue: get_venue,
create_venue: create_venue,
list_prize: list_prize,
get_prize: get_prize,
create_prize: create_prize
};
function persist_venue() {
window.localStorage['venue'] = angular.toJson(venue);
}
function list_venue() {
return venue;
}
function get_venue(venueId) {
for (var i = 0; i < venue.length; i++) {
if (venue[i].id === venueId) {
return venue[i];
}
}
return undefined;
}
function create_venue(venueItem) {
venue.push(venueItem);
persist_venue();
}
function list_prize() {
return prize;
}
function get_prize(prizeId) {
for (var i = 0; i < prize.length; i++) {
if (prize[i].id === prizeId) {
return prize[i];
}
}
return undefined;
}
function create_prize(prizeItem) {
venue.push(prizeIem);
persist_prize();
} });
i like this approach because on the top you can see all the functions available in this factory nice and easy,
and you can also reuse every function you expose outside, inside also, so its very effective and organized,
hope that helped,
good luck.

Working with promise - angularjs

How to rewrite this code, to get the desired o/p.
I would like to use the AgentReply object after filling in the data.
Inside the switch case, this object has data. But once outside, it is null again. Understood that it is because of the async,
But what should I do, to be able to use 'AgentReply' once it has data.
$scope.ActionItems = function (actionItem) {
var AgentReply = {};
switch (actionItem) {
case "SendOTP":
var SentStatus = "";
DataFactory.SendOTP('39487539847')
.then(function (response) {
SentStatus = JSON.parse(JSON.parse(response.data));
SendOTPFailed();
}, function (error) {
});
break;
}/*End of switch*/
function SendOTPFailed(){
if (SentStatus == "200") {
AgentReply = {
IsCustomer: false,
UserText: "Request Failed.",
}
}
}
if (Object.keys(AgentReply).length > 0) {
//do something with AgentReply
}
}
Just pass a function in to where the AgentReply is available, and define it underneath, ie:
$scope.ActionItems = function (actionItem) {
var AgentReply = {};
switch (actionItem) {
case "SendOTP":
var SentStatus = "";
DataFactory.SendOTP('39487539847')
.then(function (response) {
SentStatus = JSON.parse(JSON.parse(response.data));
if (SentStatus == "200") {
AgentReply = {
IsCustomer: false,
UserText: "Request Failed.",
}
}
doSomethingWithAgentReply(AgentReply);
}, function (error) {
});
break;
}
console.log(AgentReply); //null here
function doSomethingWithAgentReply(reply) {
if (Object.keys(reply).length > 0) {
//do something with AgentReply
}
}
}
If you need to use this code :
if (Object.keys(AgentReply).length > 0) {
//do something with AgentReply
}
}
Outside the .then() function :
DataFactory.SendOTP('39487539847')
.then(function (response) {
})
You can try this:
$scope.ActionItems = function (actionItem) {
var def = jQuery.Deferred();
var AgentReply = {};
switch (actionItem) {
case "SendOTP":
var SentStatus = "";
DataFactory.SendOTP('39487539847')
.then(function (response) {
SentStatus = JSON.parse(JSON.parse(response.data));
if (SentStatus == "200") {
AgentReply = {
IsCustomer: false,
UserText: "Request Failed.",
}
def.resolve(AgentReply);
}
console.log(AgentReply); //available here
}, function (error) {
def.reject(error);
});
return def.promise();
break;
}
//console.log(AgentReply); //null here
//if (Object.keys(AgentReply).length > 0) {
//do something with AgentReply
// }
//}
// This is unusable in this case.
The usage is:
var someActionItem = 'SomeActionItemInfo';
$scope.ActionItems(someActionItem)
.then(function(agentReply) {
if (Object.keys(agentReply).length > 0) {
//do something with agentReply
}
}, function(error));
EDIT:
$scope.ActionItems is the same function. What happening when you using promise?
First you defining the deffer object. var def = jQuery.Deferred(). This object is at jQuery, but all frameworks/libraryies that support promise working at the same way.
As you see, you returning def.promise(). That is the object which contain .then property. Because of that obj you can use $scope.ActionItems().then() method. That actually make def.promise().
And inside your async code (this code that consuming some time and it's not executed immediately) you defining def.resolve() or def.reject().
When the work is done. You calling def.resolve(withSomeData) and this will activate .then() method to the $scope.ActionItems.
For example:
var foo = null;
function doPromise() {
var def = jQuery.Deferred();
setTimeout(function(){
foo = 2;
def.resolve(foo + 1) // This will call the .then() method with foo + 1
}, 500);
return def.promise();
}
doPromise();
console.log(foo) // foo = null here. cuz the function waiting 500ms.
// Here the .then() method will be executed after ~500+ ms.
doPromise().then(function(fooValue) {
console.log(fooValue) // foo value = 3 here. cuz function is done
});

Resources