Sort firebase object based on time stamp - angularjs

I am developing chat application using Firebase. In my chat application i have chat Inbox.I need to sort the inbox chat based on time stamp.
To load the object from Firebase i am using following code:
var chatwith = new Firebase(firbaseUrl+'/chatInbox/'+$scope.userId);
var list = $firebaseArray(chatwith);
list.$loaded().then(function() {
$scope.dataList = list;
$scope.dataLength = $scope.dataList.length;
if (!$scope.$$phase) $scope.$apply();
});
I need to sort the $scope.dataList object based on the time stamp. is it possible?
Please suggest

to answer your question
I need to sort the $scope.dataList object based on the time stamp. is it possible?
yes it's possible , you could use orderByChild like this
var chatwith = new Firebase(firbaseUrl+'/chatInbox/'+$scope.userId);
chatwith = chatwith.orderByChild('NAME_OF_THE_FIELD_TIMESTAMP');
var list = $firebaseArray(chatwith);
list.$loaded().then(function() {
$scope.dataList = list;
$scope.dataLength = $scope.dataList.length;
if (!$scope.$$phase) $scope.$apply();
});
just don't forget to Defin Data Indexes on production like this
{
"rules": {
"chatInbox": {
".indexOn": ["NAME_OF_THE_FIELD_TIMESTAMP", "OTHER_FIELD"]
}
}
}

Related

Trying to call an API using a trigger and get data

I am very new at this and I am trying my best to work it out. It would be glad if someone can really save my day.
Trying to call an API using a trigger and get data using google scripts this is the best I came up with.
Basically I have an api which gives me objects if I putit in Postman. All I need to do it get those object in google spreadsheets.
I have tried onOpen function which was giving me an error of" You do not have permission to call Fetch".
So have been trying with on edit of first column as "Get Data" so the api can be called.
Thanks in advance
function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == "Sheet1") { //checks that we're on the correct sheet
var r = s.getActiveCell();
//Updates timestamp for lead entry and meetings.
var currentCellValue = r.getValue();
var user = Session.getEffectiveUser();
if (r.getColumn() == 1 && (currentCellValue == 'Get Data')) { //checks the column
var nextCell = r.offset(0, 4);
if (nextCell.getValue() == '') { //is empty?
nextCell.setValue(Utilities.formatDate(new Date(), "GMT+5:30", "dd/MM/yyyy HH:mm:ss")).setComment(user);
var url = "My API";
var headers = {
"Content-Type": "application/json",
"Authorization": "userkey"
};
var options = {"method":"GET","headers": headers
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response[0]);
}
}
}
}
This appears to be a long standing issue that still hasn't been taken care of, see here
Someone in the thread mentions
But, using a custom function name like myOnEdit(), and connecting it
to the onEdit event manually, totally works!
function myOnEdit(e) { ... var x = fetchUrlApp.fetch(...); ... }
So you have to create myOnEdit and then put an onEdit trigger on it, either via Resources > Current Project's triggers or via the trigger service.

Create a favorite list in Ionic Framework

I am very new to Ionic Framework. I am learning the framework and have tried to build a simple android app, which displays a simple list using json. Now, I want add a favorite list which will show user selected items in it. When user clicks on a button it should add that item in a favorite list. And When user click on Favorite tab it should show list of all favorite items.
At present I am trying to do this with simple json and global controller. But I am afraid if this is used on android app on a phone it will not store all favorites, it would remove all favourites once app is closed. Can anyone please suggest a better approach towards it.
Many thanks in advance.
I see you tagged the question with local storage, so why not use that? Also, you could use one of the popular mBaaS solutions like Firebase or gunDB.
As for the logic, it's quite easy: you create a new array which you use for storing these favorites (you handle the adding/removing on the favorite button click). You then use the ng-repeat on the Favorites tab to list the favorites array.
The best way to do this would be pouchdb, i m using in same way.!
Install pouchdb using command:
bower install pouchdb
add below line in index.html
<script src="lib/pouchdb/dist/pouchdb.min.js"></script>
make a service:
.factory('FavService', function (UserService) {
var FavService = {};
var localDB;
var user = UserService.getUser();
if (user) {
localDB = new PouchDB('u_' + user.id);
}
FavService.configDbs = function () {
//console.log('config dbs');
var user = UserService.getUser();
if (user) {
localDB = new PouchDB('u_' + user.id);
}
};
FavService.storeToLocal = function (product) { //change function name
if (localDB && product !== "") {
localDB.post(product);
// console.log("Action completed");
} else {
// console.log("Action not completed");
}
};
FavService.getLocalList = function (callback) {
if (localDB) {
localDB.allDocs({
include_docs: true
}).then(function (response) {
// console.log("response :"+JSON.stringify(response));
localDB = response.rows;
callback(response.rows);
}).catch(function () {
callback(null);
});
} else {
FavService.configDbs();
}
};
});

Saving and Getting Data / Rows to and from PouchDB

i am very new to pouchdb, meaning i have not yet been successfully able to implement an app that uses it.
This is my issue now, in my controller i have two functions:
var init = function() {
vm.getInvoicesRemote(); // Get Data from server and update pouchDB
vm.getInvoicesLocal(); // Get Data from pouchDB and load in view
}
init();
Basically in my app i have a view that shows customer invoices, now i want customers to be able to still see those invoices when they're offline. I have seen several examples of pouchdb and couchdb but all use the "todo" example which does not really give much information.
Now i'm just confused about what the point was in me spending hours understanding couchdb and installing it if in the end i'm just going to be retrieving the data from my server using my API.
Also when the data is returned how does pouchdb identify which records are new and which records are old when appending.
well, i m working on same kind..!this is how i m making it work..!
$scope.Lists = function () {
if(!$rootScope.connectionFlag){
OfflineService.getLocalOrdersList(function (localList) {
if(localList.length > 0) {
$scope.List = localList;
}
});
}else{
if(!$scope.user){
}else {
Common.callAPI("post", '***/*************', $scope.listParams, function (data) {
if (data !== null) {
$scope.List = data.result;
OfflineService.bulkOrdersAdd_updateLocalDB($scope.List);
}
});
}
}
};
so,$scope.List will be filled if online as well as offline based on connectionFlag
note : OfflineService and Common are services.
call method:
$ionicPlatform.ready(function () {
OfflineService.configDbsCallback(function(res) {
if(res) {
$scope.Lists();
}
});
});
u can try calling $scope.Lists(); directly..!
hope this helps u..!

Connection state with doowb/angular-pusher

I am trying to build an Angular project with Pusher using the angular-pusher wrapper. It's working well but I need to detect when the user loses internet briefly so that they can retrieve missed changes to data from my server.
It looks like the way to handle this is to reload the data on Pusher.connection.state('connected'...) but this does not seem to work with angular-pusher - I am receiving "Pusher.connection" is undefined.
Here is my code:
angular.module('respondersapp', ['doowb.angular-pusher']).
config(['PusherServiceProvider',
function(PusherServiceProvider) {
PusherServiceProvider
.setToken('Foooooooo')
.setOptions({});
}
]);
var ResponderController = function($scope, $http, Pusher) {
$scope.responders = [];
Pusher.subscribe('responders', 'status', function (item) {
// an item was updated. find it in our list and update it.
var found = false;
for (var i = 0; i < $scope.responders.length; i++) {
if ($scope.responders[i].id === item.id) {
found = true;
$scope.responders[i] = item;
break;
}
}
if (!found) {
$scope.responders.push(item);
}
});
Pusher.subscribe('responders', 'unavail', function(item) {
$scope.responders.splice($scope.responders.indexOf(item), 1);
});
var retrieveResponders = function () {
// get a list of responders from the api located at '/api/responders'
console.log('getting responders');
$http.get('/app/dashboard/avail-responders')
.success(function (responders) {
$scope.responders = responders;
});
};
$scope.updateItem = function (item) {
console.log('updating item');
$http.post('/api/responders', item);
};
// load the responders
retrieveResponders();
};
Under this setup how would I go about monitoring connection state? I'm basically trying to replicate the Firebase "catch up" functionality for spotty connections, Firebase was not working overall for me, too confusing trying to manage multiple data sets (not looking to replace back-end at all).
Thanks!
It looks like the Pusher dependency only exposes subscribe and unsubscribe. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L86
However, if you access the PusherService you get access to the Pusher instance (the one provided by the Pusher JS library) using PusherService.then. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L91
I'm not sure why the PusherService provides a level of abstraction and why it doesn't just return the pusher instance. It's probably so that it can add some of the Angular specific functionality ($rootScope.$broadcast and $rootScope.$digest).
Maybe you can set the PusherService as a dependency and access the pusher instance using the following?
PusherService.then(function (pusher) {
var state = pusher.connection.state;
});
To clarify #leggetters answer, you might do something like:
app.controller("MyController", function(PusherService) {
PusherService.then(function(pusher) {
pusher.connection.bind("state_change", function(states) {
console.log("Pusher's state changed from %o to %o", states.previous, states.current);
});
});
});
Also note that pusher-js (which angular-pusher uses) has activityTimeout and pongTimeout configuration to tweak the connection state detection.
From my limited experiments, connection states can't be relied on. With the default values, you can go offline for many seconds and then back online without them being any the wiser.
Even if you lower the configuration values, someone could probably drop offline for just a millisecond and miss a message if they're unlucky.

How to stop fetching collections in backbone

Disk is my collections object. I need to stop fetching collections
customPoll: function(time){
var set_time = 0;
if(time === undefined){
set_time = 4000;
}
var route = Backbone.history.fragment.split('/');
var self = this;
if(route[0] === "disks"){
setTimeout(function() {
Disks.fetch({update:true,success: function(){
self.customPoll();
}, error: function(){
self.customPoll();
}
});
}, set_time); //TODO Need to handle efficiently...
}
}
Am trying to call this fetching in every 4 second if some condition exist other wise i need to stop calling this fetching.
var route = Backbone.history.fragment.split('/');
var smart = new Smart.model({
"id" : route[1]
});
var self = this;
smart.save(null,{
success: function(model,event,response){
model = Disks.get(route[1]).toJSON();
$('#smart-confirm-dialog').modal('hide');
self.showStatusMsg(1,"<b> S.M.A.R.T. Test : </b>S.M.A.R.T Test started succesfully");
if(model.smart.progress === "100%"){
self.clearAllTimeout();
alert("please stop fetching....pleaseeee");
// Stop polling here . then fetch information from smart.fetch api.
Smart.fetch({update: true}); //this is another api i need to call this api now.
}else{
self.customPoll();
}
});
But it seems to be not working... Its keep on fetching collection.. How can i stop this Disk collection fetching.
My answer maybe is funny, I want to add comment, but I couldn't. can you add new field to your model and
customPoll: function(time){
var disks = this.model.toJSON();
if(disks.yourField){
// here your code
}
}
but before saving the model need to do delete disks.yourField;

Resources