Getting the phoneNumber using $cordovaContacts - angularjs

I'm trying to get all the contacts in the phone using ng-cordova, I success to do that like the following, I create a service in AngularJS:
.factory("ContactManager", function($cordovaContacts) {
return {
getContacts: function() {
var options = {};
options.filter = "";
options.multiple = true;
//get the phone contacts
return $cordovaContacts.find(options);
}
}
})
Also the method find in the ng-cordova is't like the following:
find: function (options) {
var q = $q.defer();
var fields = options.fields || ['id', 'displayName'];
delete options.fields;
navigator.contacts.find(fields, function (results) {
q.resolve(results);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
}
And did the following inside the controller:
ContactManager.getContacts().then(function(result){
$scope.users= result;
}, function(error){
console.log(error);
});
I noticed that in the $scope.users I find the formatted, middleName ..., but I can't find the phoneNumber, how can I get also the phoneNumbers?

If you log the contacts you should see an object with a phoneNumbers array in it.
ContactManager.getContacts().then(function(result){
$scope.users= result;
console.log(result);
...
If you don't it's something else.
I also made a somewhat close mock json of what the return looks like.

Related

deferred.resolve() is not iterating the last element inside a forloop

in the model.findone i'm getting a array which consists of 3 elements. In the else part i'm looping through each item & fetching offering head of that particular item.
But i'm able to get only 2 offering heads.Not able to fetch the last offering head.
Is there any problem with my code??
function getOfferingsHeads(id) {
var deferred = Q.defer();
var offeringHeads = [];
model
.findOne({ _id: id })
.exec(function (err, item) {
if(err) {
console.log(err);
deferred.reject(err);
}
else {
// deferred.resolve(item.offerings);
// var offeringsList = [];
// offeringsList = item.offerings;
for (var i = 0; i < item.offerings.length; i++) {
executivesModel
.findOne({offName: item.offerings[i] })
.exec(function(err1, item1) {
if(err1){
console.log(err1);
deferred.reject(err1);
}
else{
offeringHeads.push(item1.offHead);
deferred.resolve(offeringHeads);
}
});
}
}
});
return deferred.promise;
}
You can't resolve a deferred more than once, and in general you shouldn't be using deferreds at all. Since mongoose has a promise-friendly API, you should just use that. It will make your code much much cleaner:
function getOfferingHead(offName) {
return executivesModel
.findOne({offName: offName })
.exec()
.then(function (item) {
return item.offHead;
});
}
function getOfferingsHeads(id) {
return model
.findOne({ _id: id })
.exec()
.then(function (item) {
return Q.all(item.offerings.map(getOfferingHead));
});
}
To use the function:
getOfferingsHeads('myId').then(function (heads) {
console.log(heads);
});
Not sure this is what you intended but you are resolving the same promise more than once.
The latest version of mongoose lets you set the Promise library to use.
Here's a correction to what I believe you meant to do:
//Somewhere near mongoose definition
mongoose.Promise = require('q').Promise;
function getOfferingsHeads(id) {
var offeringHeads = [];
return model
.findOne({ _id: id })
.then(function (item) {
if(!item) {
//Handle no results
return Q.reject()
}
else {
return Q.all(item.offerings.map(function(offering){
executivesModel
.findOne({offName: offering.name})
}));
}
});
}
//Now you can use
getOfferingsHeads('someId').then(function (offerings) {
...
});

Downloading data to Angular from Another URL

I am new to Angular and need to download data into a service. It works fine with local json file; however, obviously you want to get the data from another URL which then gives the issue of cross domain download. Is there a way to go around this? I need to download the data from here http://files.parsetfss.com/c2e487f5-5d96-43ce-a423-3cf3f63d9c5e/tfss-31564b7d-6386-4e86-97c5-cca3ffe988f3-phones.json rather than 'phones/phones.json' below.
'use strict';
/* Services */
function makeArray(Type) {
return function(response) {
var list = [];
angular.forEach(response.data, function(data) {
list.push(new Type(data));
});
return list;
}
}
function instantiate(Type) {
return function(response) {
return new Type(response.data);
}
}
angular.module('phonecatServices', []).
factory('Phone', function($http){
var Phone = function(data){
angular.copy(data, this);
};
Phone.query = function() {
return $http.get('phones/phones.json').then(makeArray(Phone));
}
Phone.get = function(id) {
return $http.get('phones/' + id + '.json').then(instantiate(Phone));
}
// Put other business logic on Phone here
return Phone;
});
Can this be put in the following query from parse.com (how can I write the http request bit to fit into Angular.
var query = new Parse.Query("coursesParse");
query.find({
success: function(results) {
},
error: function(error) {
}
});
You can do it this way.
Phone.query = function() {
var query = new Parse.Query("test");
query.find({
success: function(results) {
//makeArray(Phone(results));
for (var i = 0; i < results.length; i++) {
var object = {
"age": results[i].get('age'),
"carrier": results[i].get('carrier'),
"id": results[i].get('id1'),
"imageUrl": results[i].get('imageUrl'),
"name": results[i].get('name'),
"snippet": results[i].get('snippet')
};
makeArray(Phone(object));
}
},
error: function(error) {
}
});
}

Restangular no BaseUrl when do PUT

i'm using Restangular and trying to PUT some data but it seems to lose the BaseUrl.
In the config function i define the BaseUrl for Restangular and others Restangular fields.
Constants.restangularBaseUrl is http://192.168.1.100/api/
RestangularProvider.setBaseUrl(Constants.restangularBaseUrl)
.setRestangularFields({
selfLink: '_links.self.href',
id: '_id',
etag: '_etag'
})
.addResponseInterceptor(function(data, operation, what, url, response, deferred){
if (operation === 'getList') {
var result = data._items;
result._meta = data._meta;
result._links = data._links;
return result;
}
return data;
});
Then i have some models like this:
(function(){
angular.module('models.ebayItems', ['services.constants', 'restangular'])
.service('EbayItems', ['Constants', 'Restangular', function (Constants, Restangular) {
Restangular.extendModel('ebayitems', function(model) {
model.toggleMonitor = function(){
var item = this;
Restangular.one('ebayitems', this._id).patch({active: this.active}, '', {'If-Match': this._etag})
.then(function(data){
item._etag = data._etag;
}, function(error){
console.log('error', error);
});
};
return model;
});
var ebayItems = Restangular.all('ebayitems');
var ebayItemsOneSearch = function(_id){
return ebayItems.customGETLIST('', {where: {searchId: _id}});
};
return {
items: ebayItems,
oneSearch: ebayItemsOneSearch
};
}])
})();
Now when i try to do a put request with an item based on that model:
item.put()
it uses the wrong url, i mean it loses the BaseUrl, so instead of putting at:
http://192.168.1.100/api/ebayitems/12345
it puts at
http://192.168.1.100/ebayitems/12345
resulting in a 404 error.
Why?
What am i doing wrong?
Any help really appreciated.
Thank you
The problem was that setting a selfLink field that was a relative url from the API backend it overrides the BaseUrl.
Removing that field from the config function it worked.
RestangularProvider.setBaseUrl(Constants.restangularBaseUrl)
.setRestangularFields({
id: '_id',
etag: '_etag'
})
.addResponseInterceptor(function(data, operation, what, url, response, deferred){
if (operation === 'getList') {
var result = data._items;
result._meta = data._meta;
result._links = data._links;
return result;
}
return data;
});

AngularJS service storing and updating data

I have a simple app that shows a list of people each with a link to an edit controller. The edit controller gets the person by id. Once the edit form has been submitted, the page is redirected back to the person list.
I have a method to update the service data in the callback after the server saves the person. The method I use does in fact work, however, I wasn't sure if there was a better way to achieve this. After much searching I haven't found a concrete answer so I wanted to reach out to the AngularJS community here for help.
Here is a fiddle: http://jsfiddle.net/7bGEG/
var app = angular.module('peopleApp',[]);
app.controller('ListCtrl',function($scope,People) {
People.getList().then(function(response) {
$scope.list = response; // show list of people with a link to new route to edit
});
});
app.controller('EditCtrl',function($scope,$location,$routeParams,People) {
// edit route so get person by id
People.getById($routeParams.id).then(function(response) {
$scope.person = response.person;
});
// submit save person form and send back to person list
$scope.savePerson = function() {
People.savePerson($scope.person).then(function(response) {
$location.path('/');
});
}
});
app.factory('People',function($http,$q) {
var people = [];
var people_q = $q.defer();
$http.get(url).then(function(response) {
people = response.data;
people_q.resolve(people);
});
return {
getList: function() {
return people_q.promise;
},
getById: function(id) {
return $http.get(url).then(function(response) {
return response.data;
});
},
savePerson: function(person) {
return $http.post(url).then(function(response) {
// find person in person array and remove them
for (i=0; i < people.length; i++) {
if (people[i].person_id == person.person_id) {
people.splice(i,1);
break;
}
}
// add new person data
people.push(response.data);
return response.data;
});
}
}
});

How do I do custom model data parsing in backbone.js?

While using backbone to hit an api, I've found that I need to only include some of the data in the response. The webserver is giving me back metadata in addition to data concerning my objects that I don't need.
The following solution works, but doesn't feel right. Is there a standard way of doing this?
var accountsCollection = new AccountsCollection();
accountsCollection.fetch({success : function(collection){
var results = new AccountsCollection();
collection.each(function(item){
results.add(new AccountModel({
id: item.toJSON().result[0].id,
messageText: item.toJSON().messageText,
address1: item.toJSON().result[0].address1,
address2: item.toJSON().result[0].address2
}));
});
onDataHandler(results);
}});
EDIT: This was my final solution based on the accepted answer:
parse: function(response) {
var accounts = [];
_.each(response['result'], function (account) {
accounts.push(account);
});
return accounts;
}
You could try overriding the Backbone.Collection.parse method and do some crazy underscore stuff. No idea if it fits your data..
var keysILike = ['foo', 'bar'];
AccountsCollection.extend({
parse: function(response) {
return _.compact(_.flatten(_.map(response, function (model) {
var tmp = {};
_.each(_.keys(model), function (key) {
if (_.contains(keysILike, key)) tmp[key] = model[key];
})
return tmp;
})));
}
});
With respect to #Sushanth's awesomeness you definitely want to use this solution:
var keysILike = ['foo', 'bar'];
AccountsCollection.extend({
parse: function(response) {
_.each(response, function (model) {
_.each(_.keys(model), function (key) {
if (!_.contains(keysILike, key)) delete model[key]
})
});
return response;
}
});

Resources