Load default data - javascript

I just started building an app using the Ionic Framework. But it basically uses Angular.js so the question should be easy to answer :)
The challenge: I have a list of dummy contacts which I can get from a ContactService. Now I'd like to get the actual contacts of my phone. The problem is, that I have to wait for the app to load before I can access the contacts. So I have to wrap it inside an event listener. This is my code, how can I make it work (the success function gets an array of contacts, I checked that)?
document.addEventListener('deviceready', function() {
StatusBar.styleDefault();
function onSuccess(contacts) {
ContactService.add(contacts);
};
function onError(contactError) {
alert('onError!');
};
var options = new ContactFindOptions();
options.multiple = true;
var fields = ['displayName', 'name'];
navigator.contacts.find(fields, onSuccess, onError, options);
}, false);
angular.module('starter.services', [])
.factory('ContactService', function() {
var contacts = [];
return {
add: function(result) {
contacts = result;
},
all: function() {
return contacts;
},
get: function(contactId) {
return contacts[contactId];
},
count: function() {
return contacts.length;
}
}
});

Related

Managing multiple SignalR connections in a single page

I'm experiencing intermittent signalr connection problems
sometimes it fails, sometimes it doesn't...
Here is the setup...
I have a list of orders, each order has a unique signalr connection. Currently there are 230 orders on a single page. The purpose of having a signalr connection is so users can see any real time updates on each order (who is viewing, editing, etc). I've decided to have a separate connection for each order so that I don't have to manage the order that is currently being viewed, edited, etc. So far, for the orders that have successfully connected, the updates are correct and smooth.
Here is my list with a sample of another user viewing an order (a photo of that user is being shown)
Here is my code that connects to the signalr hubs
crimeassure.factory('hubProxy', ['$rootScope', function ($rootScope) {
function hubProxyFactory(hubName) {
var _hubConnection = $.hubConnection();
_hubConnection.logging = true;
var _hubProxy = _hubConnection.createHubProxy(hubName);
return {
on: function (eventName, callback, failCallback) {
_hubProxy.on(eventName, function (result) {
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
})
},
invoke: function (methodName, data) {
_hubProxy.invoke(methodName, data)
.done(function (result) {
//$rootScope.$apply(function () {
// if (callback) {
// callback(result);
// }
//});
});
},
start: function (successCallback, failCallback) {
_hubConnection.start({ transport: 'webSockets' }).done(successCallback).fail(failCallback);
},
hubConnection: _hubConnection,
};
};
return hubProxyFactory;
}]);
crimeassure.directive('componentLiveUpdates', function () {
return {
restrict: 'E',
scope: {
componentId: '=',
},
templateUrl: '/scripts/templates/directive-templates/component-live-updates.html',
controllerAs: 'vm',
bindToController: true,
controller: ["$scope", "$rootScope", "appData", "hubProxy",
function componentLiveUpdates($scope, $rootScope, appData, hubProxy) {
var vm = (this);
var user = appData.getCurrentUser();
vm.componentActivity = [];
var reQueueHub = hubProxy('researcherExpressQueueHub');
var componentActivityChanged = function (component) {
if (component.ActivityValue === 'ComponentModalClose') {
var idx = vm.componentActivity.indexOf(component);
vm.componentActivity.splice(idx, 1);
}
if (component.ActivityValue === 'ComponentModalOpen') {
vm.componentActivity.push(component);
}
}
var successCallback = function () {
console.log('connected to signalR, connection ID =' + reQueueHub.hubConnection.id + '--' + vm.componentId);
reQueueHub.invoke('joinGroup', vm.componentId);
$rootScope.reQueueHubs.push({
ComponentId: vm.componentId,
Hub: reQueueHub
});
}
var failCallback = function (e) {
console.log('Error connecting to signalR = ' + vm.componentId);
console.log(e);
//startHubConnection();
}
var startHubConnection = function () {
reQueueHub.start(successCallback, failCallback);
}
var initialize = function () {
reQueueHub.on('updateComponentActivity', componentActivityChanged);
startHubConnection();
}
initialize();
}],
}
});
and here is my hub class
public class ResearcherExpressQueueHub : Hub
{
public void UpdateComponentActivity(ComponentItem item)
{
Clients.Group(item.ComponentId.ToString()).updateComponentActivity(item);
}
public void ComponentModalOpen(ComponentItem item)
{
item.Activity = ComponentActivity.ComponentModalOpen;
Clients.Group(item.ComponentId.ToString()).updateComponentActivity(item);
}
public void ComponentModalClose(ComponentItem item)
{
item.Activity = ComponentActivity.ComponentModalClose;
Clients.Group(item.ComponentId.ToString()).updateComponentActivity(item);
}
public Task JoinGroup(string componentId)
{
return Groups.Add(Context.ConnectionId, componentId);
}
public Task LeaveGroup(string componentId)
{
return Groups.Remove(Context.ConnectionId, componentId);
}
}
so my questions are,
Why am i experiencing a disconnect "WebSocket is closed before the connection is established"
Is my approach the best way to approach this type of requirement?
Use grouping mechanisme of signalr and NOT create multiple connections for your usecase!
There are limitations from IIS and also from browsers. Some browser have a limit of 4 or 5 paralell connections. You can test it by yourself by opening multiple different browsers.
Details about grouping:
Working with groups in signalr is really simple. Details you will find here: https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups

Angular-Toaster not working in my service?

I have got to know toaster.js from this site and trying to implement it in my web app. I have done it according to the example but it doesn't work.
Here is my service where I Implemented:
function () {
angular
.module('FoursquareApp')
.factory('DataService', DataService);
DataService.$inject = ['$http','toaster'];
function DataService($http, toaster) {
.id,
venueName: venue.name,var serviceBase = '/api/places/';
var placesDataFactory = {};
var userInContext = null;
var _getUserInCtx = function () {
return userInContext;
};
var _setUserInCtx = function (userInCtx) {
userInContext = userInCtx;
};
var _savePlace = function (venue) {
//process venue to take needed properties
var minVenue = {
userName: userInContext,
venueID: venue
address: venue.location.address,
category: venue.categories[0].shortName,
rating: venue.rating
};
return $http.post(serviceBase, minVenue).then(
function (results) {
toaster.pop('success', "Bookmarked Successfully", "Place saved to your bookmark!");
},
function (results) {
if (results.status == 304) {
toaster.pop('note', "Faield to Bookmark", "Something went wrong while saving :-(");
}
else {
toaster.pop('error', "Failed to Bookmark", "Something went wrong while saving :-(");
}
return results;
});
};
I have called the library scripts in index.html and also the css files.
Any ideas of what I might be doing wrong?
Are you sure that you use toaster.js library? The popular one is toastr.js
Try to modify your code to
DataService.$inject = ['$http','toastr'];
function DataService($http, toastr) {
...
Also ensure, that you link this js file in you index.html and also refer this package in main app module definition as a second (dependency) parameter

$save gives me TypeError: undefined is not a function when saving model that is a list in angular

I am using current versions of asp.net, mvc, rest api, and angular.js. I populate my page with a list then on $save it gives me error TypeError: undefined is not a function
$scope.scacTaskPLDetails = {};
$scope.onGetTaskList = function () {
var scacTaskRes = $resource("api/ScacTaskPLDetails");
scacTaskRes.query({ taskID: scacTaskID }, function (scacTaskPL) {
$scope.scacTaskPLDetails = scacTaskPL;
});
}
/************************ Save Task **************************/
$scope.onSaveScacTask = function () {
if (!$scope.isEditing) {
$scope.$broadcast('show-errors-event');
if ($scope.TaskForm.$invalid) { return; }
$scope.$broadcast('show-errors-event');
if ($scope.TaskForm.$invalid) { return; }
}
$scope.scacTaskPLDetails.$save(function (results) {
if (results.successful) {
Notifications.success(results.serverMessage);
$scope.onReloadPage();
}
else {
Notifications.error(results.serverMessage);
}
});
}
I hope this is enough information. I have had no trouble up until now and the only thing different is that I am saving a list instead of a single object. In debugging I can see the list of objects populating the viewmodel scacTaskPLDetails.
you should use your resource to send an action to your endopint, not the response you got from the resource
try something like
var scacTaskRes = $resource("api/ScacTaskPLDetails");
$scope.scacTaskRes.$save(function (results) {
if (results.successful) {
Notifications.success(results.serverMessage);
$scope.onReloadPage();
}
else {
Notifications.error(results.serverMessage);
}
});
Thanks for the tips. I finally got it to save my collections with isArray: true
app.factory("SaveArrayOfTaskPLObjects", ['$resource', function ($resource) {
return $resource(
"api/ScacTaskPLDetails",
{},
{
save: {
method: 'POST',
isArray: true
}
}
);
}]);

Instagram OAuth login

I would like to build an app for Instagram login. The problem is that i don't know how to initialize connection with instagram client id. I had done this with OAuth.initialize(), but it doesn't work. I am recieving 'OAuthException'.
My code so far:
return {
initialize: function() {
//initialize OAuth.io with public key of the application
OAuth.initialize('e6u0TKccWPGCnAqheXQYg76Vf2M', {cache:true});
authorizationResult = OAuth.create('instagram');
console.log(authorizationResult);
},
isReady: function() {
return (authorizationResult);
},
connectInstagram: function() {
var deferred = $q.defer();
OAuth.popup('instagram', {cache:true}, function(error, result) {
if (!error) {
authorizationResult = result;
deferred.resolve();
console.log('case');
} else {
console.log('case2');
}
});
return deferred.promise;
},
clearCache: function() {
OAuth.clearCache('instagram');
authorizationResult = false;
}
For starters, the only acceptable argument for OAuth.initialize is "public key".
Remove the second parameter.

Fetch collection only one time

i've a userlist made by a fetch from parse.com and rendered by view.Once people click on item list i've insert in url the objectid. In router i've made a function "home" that make fetch from collection and call view to render.The function "userdetails" catch objectid previous insert by view in url and use it to make a get from collection. The problem is:how can i pass the collection to this function userdetails?I don't want make another fetch.
home: function() {
var self=this;
console.log("inrouterhome");
var utenti = new Usercollection();
utenti.fetch({
success: function(object) {
var page=new Homelistuser({model:object});
self.changePage(page);
},
error: function(amici, error) {
// The collection could not be retrieved.
}
});
},
userDetails: function (objectId) {
HERE I WANNA USE OBJECTID TO MAKE A GET FROM COLLECTION FETCHED IN HOME
},
It looks like it is probably a scoping issue. Try this
var Models = {};
var AppRouter = Backbone.Router.extend({
home: function() {
var self=this;
console.log("inrouterhome");
Models.utenti = new Usercollection();
Models.utenti.fetch({
success: function(object) {
var page=new Homelistuser({model:object});
self.changePage(page);
},
error: function(amici, error) {
// The collection could not be retrieved.
}
});
},
userDetails: function (objectId) {
//Models.utenti should exist as long as home came first,
// may want to write a condition that check to see if it exists and if not do fetch.
}
});
As #abritez mentioned this is probably a scoping problem i.e. the userDetails method doesn't have access to the instantiated collection. #abritez's solution resolves this but if the user refreshes the page or accesses the route directly the collection will not be loaded.
If the collection is used between both routes consider fetching it at run time and using a listener for when it's ready:
var Models = {};
Models.utenti = new Usercollection();
Models.utenti.fetch();
var AppRouter = Backbone.Router.extend({
home: function() {
var utentiLoaded = function(object) {
var page = new Homelistuser({model:object});
this.changePage(page);
}
this.listenTo(Models.utenti, 'reset', utentiLoaded);
this.listenTo(Models.utenti, 'error', function(amici, error) {
// The collection could not be retrieved.
});
if (Models.utenti.any()) {
utentiLoaded(Models.utenti);
}
},
userDetails: function(objectId) {
var utentiLoaded = function(object) {
}
this.listenTo(Models.utenti, 'reset', utentiLoaded);
this.listenTo(Models.utenti, 'error', function(amici, error) {
// The collection could not be retrieved.
});
if (Models.utenti.any()) {
utentiLoaded(Models.utenti);
}
}
});

Categories

Resources