My service is returning the function's text and not an object - angularjs

I have a service to share an object in my app... I want to post that object to the mongo db but when I call the function that should return the object it gives me the function's text.
The service is here:
angular.module('comhubApp')
.service('markerService', function () {
this.markers = [];
this.newMarker = { title: '',
description: '',
lat: '',
lon: '',
user: '',
created_at: '' };
// This is supposed to return the marker object
this.newMarker = function () {
return this.newMarker;
};
this.setTitle = function (title) {
this.newMarker.title = title;
console.log('title service set: ' + title);
};
this.setDescription = function (description) {
this.newMarker.description = description;
console.log('Description service set: ' + description);
};
this.setLat = function (lat) {
this.newMarker.lat = lat;
console.log('lat service set: ' + lat);
};
this.setLon = function (lon) {
this.newMarker.lon = lon;
console.log('lon service set: ' + lon);
};
this.reset = function () {
this.newMarker = { title: '',
description: '',
lat: '',
lon: '',
user: '',
created_at: ''};
}
this.setMarkers = function (markers) {
this.markers = markers;
}
this.markers = function () {
return this.markers;
}
this.addMarker = function (marker) {
//todo append marker
}
});
newMarker returns:
this.newMarker = function () {
return this.newMarker;
};
The Controller using the service is here
$scope.addMarker = function() {
if($scope.newMarker.title === '') {
console.log('newMarker title is empty');
return;
}
markerService.setTitle($scope.newMarker.title);
markerService.setDescription($scope.newMarker.description);
console.log(markerService.newMarker());
// $http.post('/api/markers', { name: $scope.newMarker });
// $scope.newMarker = '';
};
$scope new marker is form data.. i tried to put that right into my service with no success. Instead I out the form data into the controller then push it to the service. If there is a better way to do that please let me know.
If this service is bad in any other way let me know I am new to all this and so I followed another answer I saw on here.

You are overriding your object with function. Just give them different names and it should work just fine.
this.newMarker = { ... };
this.getNewMarker = function () { return this.newMarker };
EDIT:
You should also always create new instance from marker. Otherwise you just edit the same object all the time. Here is example I made. Its not best practice but hope you get the point.
angular.module('serviceApp', [])
.factory('Marker', function () {
function Marker() {
this.title = '';
this.descrpition = '';
}
// use setters and getters if you want to make your variable private
// in this example we are not using these functions
Marker.prototype.setTitle = function (title) {
this.title = title;
};
Marker.prototype.setDescription = function (description) {
this.description = description;
};
return Marker;
})
.service('markerService', function (Marker) {
this.markers = [];
this.getNewMarker = function () {
return new Marker();
}
this.addMarker = function (marker) {
this.markers.push(marker);
}
})
.controller('ServiceCtrl', function ($scope, markerService) {
$scope.marker = markerService.getNewMarker();
$scope.addMarker = function () {
markerService.addMarker($scope.marker);
$scope.marker = markerService.getNewMarker();
}
$scope.markers = markerService.markers;
});
You could also create Marker in controller and use markerService just to store your object.
And working demo:
http://jsfiddle.net/3cvc9rrs/

So, that function is the problem. I was blindly following another example and it was wrong in my case. The solution is to remove that function and access markerService.newMarker directly.
I am still a big enough noob that I am not sure why the call was returning the function as a string. It seems to have something to do with how it is named but it is just a guess.

Related

An empty array is returned when calling $http.get it within a service [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get the name from an array that is being generated from $http.get, however this is returning an empty array. When i do a console it see the array populated however when i loop inside the array to get the value of name property based on whether an id is equal to a certain, the array is empty.
In my controller i have a service call that shall return the name value.
var params = { Id: $scope.Id, SettingId: $scope.SettingId };
$scope.selectedUserName = helloService.getSelectedUserName($scope.UserId, params);
In my service
I have used the getUserList function to populate the list of user in a dropdown and it works by generating the array with the values.
However When i got another page , i want to be able to display the name of the selected user, so I wanted to use the same getUserList function to retrieve the name
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
var promise = $http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
return usersObj;
};
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Array length is 0 but if i do a console.log(userList) before the loop , the array display the list of user data
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
console.log(userList) ;
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Thank you for kind responses.
Please see screenshot
This is simple Javascript, not specific to Angular. You can do
userList.forEach(user => {
if(user.userId === id) {
name = user.name;
}
});
return name;
you can try like this.
here we are using a async await.
Service
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
return new Promise((resolve, reject) => {
$http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
resolve(usersObj);
});
};
this.getSelectedUserName = async function (id, param) {
var name = "";
var userList = await this.getUserList(param);
console.log(userList);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
let me know if it is working or not.
EDIT:
If you're only trying to match one id in the array of users you don't even need to loop:
anArray = source.filter(source => source.toLowerCase().indexOf(id) === 0);
or
anObject = source.find(obj => obj.id === id);
Which Angular version is this? Your tag denotes 2.+ but you have $scope there which is ng1.x
Why can't you use ngFor in your view since you already have your arrays. You don't need to sort them in the control.
component
this.getSelectedUserName = function (id, param) {
let name = ""; // should be array if you want to add unames to it
let userList = this.getUserList(param);
// what is `angular` here? And why loop here? Use ngFor in view.
angular.forEach(userList, function (value, key) {
if (value.userId == id){
name = value.name; // will be overwritten each time
// should be name.push(value.name); // but loop in view instead
}
});
// this.users = name; // for your original sorted version
this.users = userList;
}
In your view
<li *ngFor="let user of users; index as i;>
{{user.name}}
</li>

Why my array is still empty even though I had assign value to this array in my controller? (I am using angularjs, not angular)

This question took me one day to debug it, but still no luck.
Problem: this.gridOptions.data = this.allTemplatesFromClassificationRepo ;
**this.allTemplatesFromClassificationRepo ** is still a empty array. Before this line of code executes, I have call activate() function to assign array to **this.allTemplatesFromClassificationRepo **. Please see this line this.allTemplatesFromClassificationRepo = templateReorderProperties;
P.S. Although I cannot get the value of allTemplatesFromClassificationRepo in controller, but I can get the value of it in html.
namespace app.admin {
'use strict';
class FooController {
static $inject: Array<string> = [];
constructor() {
this.activate();
}
activate() {
this.getData();
this.classificationFoo = this.data[0];
this.getTemplateFromGivenRepo(this.classificationFoo.id, this.classificationFoo.displayName);
this.populateData();
}
data: any;
classificationFoo: any;
allDataFromclassificationFoo: any = [];
// demo grid
gridOptions = {
enableFiltering: true,
},
data: []
};
populateData() {
this.gridOptions.data = this.allTemplatesFromClassificationRepo ;
}
getData() {
this.fooService.getUserData();
this.data = this.fooService.userdata;
}
getTemplateFromGivenRepo(fooId: string, fooName: string) {
switch (fooId) {
case 'FOO':
this.TemplateApi.templatesAvaiableForRepoIdGET(fooId).then(data => {
data.forEach(element => {
element.fooName = fooName;
});
let templateReorderProperties = data
this.allTemplatesFromClassificationRepo = templateReorderProperties;
}, error => {
});
break;
default:
break;
}
};
}
class Bar implements ng.IDirective {
static $inject: Array<string> = [];
constructor() {
}
bindToController: boolean = true;
controller = FooController;
controllerAs: string = 'vm';
templateUrl: string = 'app/foo.html';
static instance(): ng.IDirective {
return new Bar();
}
}
angular
.module('app.admin')
.directive('bar', Bar.instance);
}
getTemplateFromGivenRepo is async operation.
Move this.populateGridData(); call inside getTemplateFromGivenRepo after
this.allTemplatesFromClassificationRepo = templateReorderProperties;
getTemplateFromGivenRepo(repoId: string, repoName: string) {
switch (repoId) {
case 'CLASSIFICATION':
this.TemplateApi.templatesAvaiableForRepoIdGET(repoId).then(data => {
this.allTemplatesFromClassificationRepo = templateReorderProperties;
this.populateGridData(); // call here
}, error => {
});
}
};
OR
You can return promise from getTemplateFromGivenRepo and in then able success callback,call
this.populateGridData();
I think the problem is in this instance that different inside Promise resolve.
Try to write in beginning something like:
var self = this;
and after that change all this to self key.
a.e.:
self.gridOptions.data = self.allTemplatesFromClassificationRepo;
// and so on ...
By this way you will guarantee that you use same scope instance
Hope it will work

Angular-jsdoc - how to document complex method

I started to use angular-jsdoc for document my AngularJS code.
I have a service with some methods.
Some of the methods, return an object with another methods:
Here is an example of my service (with simple method and complex method)
angular.module('map').service('pointUtils', function ($http) {
var self = this;
// simple function
self.removeAllPoints = function () {
// remove all points
};
// complex function
self.createPoint = function (params) {
var pointData = {
isVisible :params.isVisible || true,
color : params.color || 'blue'
};
var pointObj = {};
pointObj.setColor = function (color) {
pointData.color = color;
};
pointObj.getColor = function () {
return pointData.color;
};
pointObj.setVisible = function (visible) {
pointData.isVisible = visible;
};
return pointObj
};
});
what is the way to document this complex method?
thanks,
kfir

Unable to get my data from $firebaseObject using AngularFire in a controller. View/ng-repeat works fine

I have different sections in Firebase with normalized data, and I have routines to get the information, but I cannot loop through the returned records to get data. I want to use the keys in the $firebaseArray() to get data from other $firebaseObject().
GetOneTeam() .... {
var DataRef = GetFireBaseObject.DataURL(Node + '/'); // xxx.firebaseio.com/Schedules/
var OneRecordRef = DataRef.child(Key); // Schedule Key - 1
return $firebaseObject(OneRecordRef);
}
...
var Sched = GetOneSchedule('Schedules', 1);
... // For Loop getting data - Put in HomeId
var TeamRec = GetOneTeam('Teams', HomeId);
var Name = TeamRec.TeamName; // Does not TeamName value from Schedule/1
The following is more of the actual code in case the snippet above is not clear enough. Sample common routine for getting data:
angular.module('MyApp')
.constant('FIREBASE_URL', 'https://xxxxxxxx.firebaseio.com/');
angular.module('MyApp')
.factory('GetFireBaseObject', function(FIREBASE_URL) {
return {
BaseURL: function() {
return new Firebase(FIREBASE_URL);
},
DataURL: function(Node) {
return new Firebase(FIREBASE_URL + Node);
}
};
}
);
// Common code for getting Array/Object from Firebase.
angular.module('MyApp')
.factory("FireBaseData", ["$firebaseArray", "$firebaseObject", "GetFireBaseObject",
function($firebaseArray, $firebaseObject, GetFireBaseObject) {
return {
AllRecords: function(Node) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
return $firebaseArray(DataRef);
},
OneRecordAllChildren: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var ParentRecordRef = DataRef.child(Key);
return $firebaseArray(ParentRecordRef);
},
OneRecord: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var OneRecordRef = DataRef.child(Key);
return $firebaseObject(OneRecordRef);
},
AddRecord: function(Node, Record) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var AddRecordRef = DataRef.child(Record.Key);
AddRecordRef.update(Record);
return $firebaseObject(AddRecordRef); // Return Reference to added Record
},
DeleteRecord: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var DeleteRecordRef = DataRef.child(Key);
DeleteRecordRef.remove();
}
};
}
]);
Individual Controller's retrieval of records from firebase.io:
angular.module('MyApp').service("ScheduleData", ["FireBaseData",
function(FireBaseData) {
var DataPath = 'Schedules';
this.AllSchedules = function() {
return FireBaseData.AllRecords(DataPath);
};
this.AddSchedule = function(GameInfo) {
return FireBaseData.AddRecord(DataPath, GameInfo);
};
this.DeleteSchedule = function(GameKey) {
FireBaseData.DeleteRecord(DataPath, GameKey);
};
this.GetOneSchedule = function(GameKey) {
return FireBaseData.OneRecord(DataPath, GameKey);
};
}
]);
// Structure of a record, including named fields to come from another object (Team/Venue using the OneRecord FireBaseData call to get a $firebaseObject
angular.module('MyApp').factory("ScheduleRecord", function() {
return {
Clear: function(GameInfo) {
GameInfo.Key = "";
GameInfo.HomeTeamId = "";
GameInfo.HomeTeamName = "";
GameInfo.AwayTeamId = "";
GameInfo.AwayTeamName = "";
GameInfo.VenueId = "";
GameInfo.VenueName = "";
GameInfo.GameDate = "";
GameInfo.GameTime = "";
}
};
}
);
Controller module start:
angular.module('MyApp').controller('ScheduleCtrl', ["$scope", "ScheduleData", "ScheduleRecord", "TeamData", "VenueData",
function ($scope, ScheduleData, ScheduleRecord, TeamData, VenueData) {
var ClearEditData = function() {
$scope.ScheduleEditMode = false;
ScheduleRecord.Clear($scope.schedule);
};
var GameSchedules = ScheduleData.AllSchedules();
This next piece is where my question lies. Once the promise returns the static schedule list, I want to loop through each record and translate the Team Id (Home/Away) and Venue Id to the names.
GameSchedules.$loaded().then(function() {
angular.forEach(GameSchedules, function(GameInfo) {
var HomeTeam = TeamData.GetOneTeam(GameInfo.HomeTeamId);
GameInfo.HomeTeamName = HomeTeam.Name;
The GetOneTeam returns a $firebaseObject, based on the HomeTeamId child record. This returns null all the time.
This is the TeamData.GetOneTeam return using the FireBaseData as well.
angular.module('MyApp').service("TeamData", ["FireBaseData",
function(FireBaseData) {
var DataPath = 'Teams';
this.AllTeams = function() {
return FireBaseData.AllRecords(DataPath);
};
this.AddTeam = function(TeamInfo) {
return FireBaseData.AddRecord(DataPath, TeamInfo);
};
this.DeleteTeam = function(TeamKey) {
FireBaseData.DeleteRecord(DataPath, TeamKey);
};
this.GetOneTeam = function(TeamKey) {
return FireBaseData.OneRecord(DataPath, TeamKey);
};
}
]);
As I have a Firebase Object, how can I get my named data objects from the $firebaseObject?
This is a mess. Use $firebaseArray for collections, not $firebaseObject. Most of these strange wrapper factories are unnecessary. AngularFire services already have methods for add, remove, and so on, and all these factories attempt to make AngularFire into a CRUD model and don't actually provide any additional functionality or enhancements.
app.factory('Ref', function(FIREBASE_URL) {
return new Firebase(FIREBASE_URL);
});
app.factory('Schedules', function($firebaseArray, Ref) {
return $firebaseArray(Ref.child('Schedules'));
});
// or if you want to pass in the path to the data...
//app.factory('Schedules', function($firebaseArray, Ref) {
// return function(pathToData) {
// return $firebaseArray(Ref.child(pathToData));
// };
//});
app.factory('Schedule', function($firebaseObject, Ref) {
return function(scheduleId) {
return $firebaseObject(Ref.child('Schedules').child(scheduleId));
}
});
app.controller('...', function(Schedules, Schedule, Ref) {
$scope.newSchedule(data) {
Schedules.$add(data);
};
$scope.removeSchedule(key) {
Schedules.$remove(key);
};
$scope.updateSchedule(key, newWidgetValue) {
var rec = Schedules.$getRecord(key);
rec.widgetValue = newWidgetValue;
Schedules.$save(rec);
};
// get one schedule
var sched = Schedule(key);
sched.$loaded(function() {
sched.widgetValue = 123;
sched.$save();
});
});

Knockout model breaking on array length in computed observable

Slowly extending my nested form at http://jsfiddle.net/gZC5k/1004/ I'm running into a difficulty getting to work ko.computed that I want to use to compute the number of children in the nested JSON array. The code that breaks is at // this breaks
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return {
firstName: ko.observable(contact.firstName),
lastName: ko.observable(contact.lastName),
isKey: ko.observable(contact.isKey),
gender: ko.observable(contact.gender),
phones: ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) {
return {
type: ko.observable(phone.type),
number: ko.observable(phone.number),
calls: ko.observableArray(phone.calls),
callsVisible: ko.observable(false)
};
})),
addresses: ko.observableArray(contact.addresses),
optionGender: optionGender,
phonesVisible: ko.observable(false),
addressesVisible: ko.observable(false),
// this breaks
// numberOfPhones: ko.computed(function (contact) {
// return contact.phones.length;
// });
};
}));
Where is the error?
I think that you're going to need to create each contact as a function:
var ContactModel = function(contact)
{
var self = this;
self.firstName = ko.observable(contact.firstName);
self.lastName = ko.observable(contact.lastName);
self.isKey = ko.observable(contact.isKey);
self.gender = ko.observable(contact.gender);
self. phones = ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) {
return {
type: ko.observable(phone.type),
number: ko.observable(phone.number),
calls: ko.observableArray(phone.calls),
callsVisible: ko.observable(false)
};
}));
self.addresses = ko.observableArray(contact.addresses);
self.optionGender = optionGender;
self.phonesVisible = ko.observable(false);
self.addressesVisible = ko.observable(false);
self.numberOfPhones = ko.computed(function () {
return self.phones().length;
});
return self;
};
And create it like this:
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return new ContactModel(contact);
}));
You can try this:
numberOfPhones: ko.computed(function () {
return contact.phones.length;
})

Resources