Best practice to get a json response object in angularjs - javascript

I have an API which return a json array object, right now, I get the json in my Controller like this and it works just fine :
angular.module('lyricsApp', [])
.controller('LyricsController', ['$scope', 'ApiCall', function ($scope, ApiCall) {
$scope.lyrics = {
id: "",
songName: "",
singerName: "",
writtenBy: "",
lyricText: "",
isEnable: "",
created_at: "",
updated_at: ""
};
$scope.searchLyric = function () {
var result = ApiCall.GetApiCall().success(function (lyrics) {
$scope.lyrics.id = lyrics.data.id
$scope.lyrics.singerName = lyrics.data.singerName;
$scope.lyrics.songName = lyrics.data.songName;
$scope.lyrics.writtenBy = lyrics.data.writtenBy;
$scope.lyrics.lyricText = lyrics.data.lyricText;
$scope.lyrics.isEnable = lyrics.data.isEnable;
$scope.lyrics.created_at = lyrics.data.created_at;
$scope.lyrics.updated_at = lyrics.data.updated_at;
});
}
}])
But I think this is not a good practice, I already try this :
var result = ApiCall.GetApiCall().success(function (lyrics) {
$scope.lyrics=lyrics.data;
});
in this case I get undefined value :
console.log($scope.lyrics.id); // show Undefined
So, if you guys can suggest a better way I will be appreciate it.

You are doing the right thing, except for console.log. If your log statement is executed before the assignment is done, you will get the undefined value.
Also I don't see why you would do a var result =
You can simply do
ApiCall.GetApiCall('v1', 'lyrics', '1').success(function (data) {
$scope.lyrics = data.data;
console.log($scope.lyrics.id);
}).error(fucntion(data){
console.log(data);
});

Related

calling a json array in angularjs

I have an json array of
[{
"id": "21390238becde1290",
"chelsea": {
"homeTeam": "chelsea",
"sortName": "ches",
"awayTeam": "Maribor",
"awayShort": ""
},
"barclays": {
"id": "21390238becde1290",
"homeTeam": "barclays",
"sortName": "barc",
"awayTeam": "Hull",
"awayShort": ""
}
}]
Controller:
footBallApp.controller('TeamInfoEdit',
function ($rootScope, $scope, $state, $translate, carwashService) {
$rootScope.washTypes;
$scope.onViewLoaded = function () {
matchService.getTeamTypes($scope.TypeSelected);
}
$scope.TypeSelected = function (response) {
debugger;
if (response) {
$rootScope.teamAvailable = response;
$scope.localizedTeamName = getLocalizedCollection($scope.teamAvailable);
}
}
// Editing the Team Details.
$scope.editTeamDetails = function (key) {
console.log(key._id);
$rootScope.selectTeam =[];
for(var i=0; i<$scope.teamAvailable.length;i++){
if($scope.teamAvailable[i]._id== key._id)
{
console.log($scope.teamAvailable[i]);
$scope.selectTeam.push($scope.teamAvailable[i]);
debugger;
And I have assigned the array to $scope.selectTeam. When Im trying to call $scope.selectTeam.chelsea.Im getting it as Undefined in the console. While calling the json I'm going wrong but couldn't find it, so how do I call the array correctly. So looking for help in this.
I don't know how your array looks like, but try to call:
$scope.selectTeam[0].chelsea
Array is coming because of uninitialized.
If you initialize $rootScope.teamAvailable = {}; then if response data comes in json format it will overwrite.

How to synchronize the function commands in angular js

I am creating an ionic application and in particular scenario
when an employee is selected from a list(generated from a JSON data array), his detail is to be shown from here
var employees = [{"id": 325, "firstName": "James", "lastName":
"King", "managerId": 0, "managerName": "", "reports": 4, "title":
"President and CEO", "department": "Corporate", "cellPhone":
"617-000-0001", "officePhone": "781-000-0001", "email":
"jking#gmail.com", "city": "Boston, MA", "pic": "James_King.jpg",
"twitterId": "#fakejking", "blog": "http://coenraets.org"}.....
All i need is to find the index of ID to show the complete object.
findById: function(employeeId) {
var deferred = $q.defer();
var searchValue = {'id': employeeId };
index = -1;
_.each(employees, function(data, idx) {
if (_.isEqual(data, searchValue)) {
index = idx;
return;
}
});
var employee = employees[index];
deferred.resolve(employee);
return deferred.promise;
},
for that i am using this function which is not taking debugger inside the _.each function
kindly tell me where m i wrong.
It's not going to work because expression _.isEqual(employees[xxx], {id: 325}) will never return a match.
Instead use _.find method
findById: function(employeeId) {
var employee = _.find(employees, {id: employeeId});
return $q.when(employee);
}
I think you can simplify your function a little, because you are using lodash:
findById: funtion(employeeId) {
return _.findWhere(employees, {id : employeeId});
}
Futhermore I do not see any reason to use promises here, but to go with that notion, you could try this:
findById: funtion(employeeId) {
var deferred = $q.defer();
$timeout(function() {
var employee = _.findWhere(employees, {id : employeeId});
if (found !== undefined) {
deferred.resolve(employee);
} else {
deferred.reject();
}, 0);
return deferred.promise;
}
You need to return the promise deferred.promise before you resolve() or reject(), so you can wait for that in your callee.
Hope that helps!
I don't know if your really need the index. To work on a solution, which returns the employee at that moment, when you find the data, would be better and shorter. Than you should also jump out of the loop.
If your debugger is not jumping inside _.each maybe your employees array is empty.
You could try something like this:
findById: function(employeeId) {
var deferred = $q.defer();
// deferred should be inside the scope of _.each
// because it is defined here
var searchValue = {'id': employeeId };
//index = -1;
// check your data here
// for example console.log(employees.length)
// or make a breakpoint here and check employees
_.each(employees, function(data, idx) {
// make a console.log(idx) here to check your data
if (_.isEqual(data, searchValue)) {
deferred.resolve(data);
return deferred.promise;;
}
});
},

AngularJS service parent separate reference

I'm using an AngularJS service to store data from multiple pages, to be submitted together. See the code below.
In my Chrome console if I observe checkoutData.shipping, I get back the correct object with data. If I observe checkoutData.data I get an empty object, where it's shipping property is blank.
These should be pointing at the same object, right? Why would it work with .shipping and not using .data? The reason it's set up this way is that the shipping page only cares about .shipping, while the final page needs everything in .data.
(function() {
angular.module('app').factory('checkoutData', [function() {
var data = {
carrierId: null,
serviceTypeId: null,
shippingCost: {},
billingOptionId: null,
shipping: {},
billing: {},
cart: null
};
var inputForms = {};
var options = {
shippingOptions: null,
billingOptions: null,
selectedShippingOption: null
};
var staticContent = {
billing: {},
cart: {},
shipping: {}
};
return {
data: data,
shipping: data.shipping,
inputForms: inputForms,
cart: data.cart,
billingOptionId: data.billingOptionId,
billingOptions: options.billingOptions,
carrierId: data.carrierId,
serviceTypeId: data.serviceTypeId,
shippingOptions: options.shippingOptions,
staticContentBilling: staticContent.billing,
staticContentCart: staticContent.cart,
staticContentShipping: staticContent.shipping,
selectedShippingOption: options.selectedShippingOption,
setValid: function(formName, valid) {
inputForms[formName].valid = valid;
},
initializeForm: function(formName) {
inputForms[formName] = {};
},
formInitialized: function (formName) {
return inputForms[formName] != null;
}
}
}]);
})();
One suggestion to make things easier is separate your data model(s) from your methods. And there's no need to try to keep multiple references to the same object within the same factory. There's nothing wrong with doing for example ng-model="checkoutModule.data.shipping.firstName". Is it wordier? Yes. Is it wrong? No.
So maybe something like
angular.module('app').factory('checkoutData', [function() {
return {
dataModel: {
carrierId: null,
serviceTypeId: null,
shippingCost: {},
shipping: {}, // This should be databound to an object from "shippingOptions", removing the need for "selectedShippingOption"
billing: {}, // This should be databound to an object from "billingOptions", removing the need for "billingOptionId"
cart: null
},
options: {
shippingOptions: null,
billingOptions: null
},
inputForms: {}
};
}]);
for your data and
angular.module('app').factory('checkoutModule', ['checkoutData', function(checkoutData) {
return {
data: checkoutData.dataModel,
options: checkoutData.options,
inputForms: checkoutData.inputForms,
setValid: function(formName, valid) {
checkoutData.inputForms[formName].valid = valid;
},
initializeForm: function(formName) {
checkoutData.inputForms[formName] = {};
},
formInitialized: function (formName) {
return checkoutData.inputForms[formName] != null;
}
}
}]);
for the factory that ties it all together.
From what I can see there is no way of setting the value of data.shipping other than using something like:
checkoutData.shipping = {"country" : "Sweden"};
This will result in checkoutData.shipping pointing to a new object and checkoutData.shipping will return that object:
{"country" : "Sweden"};
but
checkoutData.data will return the original empty shipping object since we haven't updated that value.
If you instead create a function for setting the shipping value in the checkoutData service:
setShipping : function(s){
data.shipping = s
},
and use that for setting the shipping data, you will get the values you want from checkout.data and checkout.shipping.
Have a look at this for demonstration: jsfiddle

Why I'm getting the var undefined

I'm trying to get a Rest array and then display it on my HTML.
the problem that I'm facing is that In My factory I'm able to get the array and display it's content, but not in my controller where I'm always getting the Undefined var. here is my Factory
.factory('coursesService', function($resource) {
var service = {};
service.getAllCouses = function (){
var Courses = $resource("/myproject/rest/training/trainings");
var data = Courses.query().$promise.then(function(data)
{
service.data= data;
console.log("ligne 1: ", service.data[0].name);
console.log("ligne 1: ", service.data[0].creator);
console.log("ligne 2: ", data[1].name);
console.log("ligne 2: ", data[1].creator);
return service.data;
});
}
return service;
})
and my controller
.controller("CoursesController",
function CoursesController($scope, coursesService) {
var courses = {};
courses = coursesService.getAllCouses();
console.log("courses: ", courses);
})
as results I'm getting this:
courses: undefined
ligne 1: Angular
ligne 1: Object {id: "1", username: "User1", email: "user1#gmail.com", password: "password", userProfile: Object}
ligne 2: JavaScript
ligne 2: Object {id: "1", username: "User1", email: "user1#gmail.com", password: "password", userProfile: Object}
Why I'm getting courses: undefined? and Shouldn't be displayed after the list that I'm displaying in the factory?
Your getAllCouses function never returns anything, and so calling it always results in undefined. The callback to the query promise then handler returns something, but not getAllCouses.
You'll need to have getAllCouses return the promise, and then use the result from within a then handler on that promise. You can't just use its return value directly, not if Courses.query() is async (and if it isn't, why is it returning a promise?).
That would look something like this:
.factory('coursesService', function($resource) {
var service = {};
service.getAllCouses = function (){
var Courses = $resource("/myproject/rest/training/trainings");
var data = Courses.query().$promise.then(function(data) {
service.data= data;
console.log("ligne 1: ", service.data[0].name);
console.log("ligne 1: ", service.data[0].creator);
console.log("ligne 2: ", data[1].name);
console.log("ligne 2: ", data[1].creator);
return service.data;
});
return data; // <=== Return the promise (`data` is a bit of a suspect name)
};
return service;
})
Then:
.controller("CoursesController", function CoursesController($scope, coursesService) {
coursesService.getAllCouses().then(function(courses) { // <=== Use the promise
console.log("courses: ", courses); // <===
}); // <===
})
...but I'm not an Angular guy.
getAllCouses() does not return a value, it just sets two local variables, Courses and data.
The Courses.query promise only resolves once the web request is complete, so those logs are delayed.
I fixed the issue by updating my service and controller like this:
.factory('coursesService', function($resource) {
return $resource("/myproject/rest/training/trainings", {
query : {
method : "GET",
isArray : true
}
});
});
I just added the
isArray : true
and i updated the controller
.controller(
"CoursesController",
function UserController($scope, coursesService) {
coursesService.query(function(data) {
console.info("data: ", data)
console.log("1st course: ", data[0].name)
$scope.Courses = data;
});
I fix it simply in this way:
.factory('coursesService', function($resource) {
return $resource("/myproject/rest/training/trainings")
})
and the controller:
.controller("coursesController", function($scope, coursesService) {
coursesService.query(function(data) {
$scope.Courses = data;
});
})

Parse Promise and Parse Relation toghether - Javascript API

Ok guys! Could someone help me?
I have a parse DB as follow:
Person(id, name)
Product(id,serial)
Invoice(id,<Relation>products, personId)
I need to build a function that returns an array of Objects,
in each Object person.name, invoice.id,invoice.products
I'm not so good with english so I wish you understand what i mean.
so i use Parse.Promise to query the "person" and the "invoice"
function Obj(name, invoiceId, products) {
return {
name: name || '',
invoiceId: invoiceId || '',
products: products || []
};
}
function retreiveData(aName) {
var retval = [],
personQuery = new Parse.Query("Person");
personQuery.equalTo('name', aName).first().then(function(person) {
var invoiceQuery = new Parse.Query("Invoice");
return invoiceQuery.equalTo('personId', person.id).query().find();
}), then(function(invoices) {
//until here everythinks work fine
// now i've the invoices list and i have to look for related products
var promise = new Parse.Promise();
_.each(invoices, function(invoice) {
var obj = new Obj(aName, invoice.id),
promise = new Parse.Promise();
invoice.relation('products').query().find().then(function(products) {
obj.products = products;
// here i expect to have the obj fulfilled with all data
retval.push(obj);
promise.resolve();
});
return promise;
});
return promise;
});
}
var aName = 'Paul';
retreiveData(aName).then(function(retval) {
console.log('success');
/* here i have to have somethin like
retval=[{
name='paul',
invoiceId='12412412',
products=[{prod1},{prod2},{prod3}]
},{
name='paul',
invoiceId='67413412',
products=[{prod5},{prod10},{prod33}]
}]
*/
});
any idea?
i know the inner promise is wrong, but i don't understand how to fix
Thanks guyz!

Categories

Resources