Ionic framework real time chat error - javascript

I am trying to make a real time chat in ionic in which the messages are logged in firebase but I'm receiving this error:
Error: $scope.chats.$add is not a function
The code it suppose to separate the messages by groups and when a message is sent it will send my chats to the firebase using $add
And here is my code:
angular.module('starter.controllers', ["ionic",'firebase'])
.controller('ChatsCtrl', ['$scope', '$stateParams', '$firebaseArray', '$rootScope', '$ionicHistory', '$state',
function($scope, $stateParams, $firebaseArray, $rootScope, $ionicHistory, $state) {
$rootScope.notifyIonicGoingBack = function() {
$state.go('groups');
}
$scope.$myBack = function() {
$ionicHistory.goBack();
$rootScope.notifyIonicGoingBack();
};
console.log('state ' + $stateParams);
var ref = new Firebase('https://projectxu.firebaseio.com/chats') //USE OUR Firebase FOR CHAT!!
$scope.sender_id = 1;
$scope.group_id = $stateParams.group_id;
var sync = $firebaseArray(ref);
sync.$loaded(function (data) {
var filtered_chats = new Array();
angular.forEach(data, function(value, key) {
if(value.group_id == $scope.group_id) {
filtered_chats.push(value);
}
});
$scope.chats = filtered_chats;
});
$scope.sendChat = function(chat){
console.log("MESSAGE SENT");
//if($rootScope.authData){
/* $scope.chats.$add({
user: $rootScope.authData.facebook.username, //SWITCH TO FACEBOOK!!!
message: chat.message,
imgURL: $rootScope.authData.facebook.cachedUserProfile.profile_img_url
});
*/
$scope.chats.$add({
sender_id: $scope.sender_id, //SWITCH TO FACEBOOK!!!
message: chat.message,
group_id: $scope.group_id,
timestamp: new Date().getTime(),
//sender_name: $rootScope.authData.facebook.cachedUserProfile.displayName,
//imgURL: $rootScope.authData.facebook.cachedUserProfile.profile_img_url
});
chat.message ="";
console.log("MESSAGE");
}
}])

Related

angularjs logged in user info to be available throughout the app

I want to make the user info available to all views after login. How can I modify the code to be able to access the pseudonym from the other view?
Can you please give an example?
Here is my login controller:
app.controller("MyregisterCtrl", ["$scope", "$stateParams", "Auth", "$state", "$location", "$modal", "DatabaseRef",
function ($scope, $stateParams, Auth, $state, $location, $modal, DatabaseRef) {
$scope.user = {};
$scope.signIn = function () {
if (!$scope.user.email && !$scope.user.password) {
toastr.error("Add email and password");
} else {
Auth.$signInWithEmailAndPassword($scope.user.email, $scope.user.password)
.then(function(firebaseUser) {
//=====user info=================
var userId = firebase.auth().currentUser.uid;
DatabaseRef.ref('/users/' + userId).once('value')
.then(function(snapshot) {
pseudonym = snapshot.val().pseudonym;
console.log("pseudonym: ", pseudonym);
return pseudonym;
});
//======================
$state.go('app.dashboard');
if (!firebaseUser.emailVerified) {
toastr.info('Your email is NOT verified.', 'Verify email!');
$state.go('login.signin');
}
})
.catch(function(error) {
toastr.error(error.message, error.reason, { timeOut: 10000 });
$scope.user = {};
})
}
};
}]);
this console.log("pseudonym: ", pseudonym); gives me what I want to access, but can't access it from other views, by just typing {{pseudonym}} for example.
Assign to a $scope variable, whenever you want to display on view ,
pseudonym = snapshot.val().pseudonym;
$scope.pseudonym =pseudonym;

angularjs firebase login scope value is not available after refresh

I have my pseudonym in the $scope and I try to access it from other views after the user has logged in, using:
however, when I refresh the page immediately after the user has successfully signed in, the $scope value reverts back into {{pseudonym}} and the parameter isn't available. How can I save this data persistently throughout the logged in session? Can you please provide the answer with an example?
app.controller("MyregisterCtrl", ["$scope", "$stateParams", "Auth", "$state", "$location", "$modal", "DatabaseRef", "$rootScope",
function ($scope, $stateParams, Auth, $state, $location, $modal, DatabaseRef, $rootScope) {
$scope.user = {};
$scope.signIn = function () {
if (!$scope.user.email && !$scope.user.password) {
toastr.error("Add email and password");
} else {
Auth.$signInWithEmailAndPassword($scope.user.email, $scope.user.password)
.then(function(firebaseUser) {
var userId = firebase.auth().currentUser.uid;
DatabaseRef.ref('/users/' + userId).once('value')
.then(function(snapshot) {
pseudonym = snapshot.val().pseudonym;
console.log("pseudonym: ", pseudonym);
$scope.pseudonym = pseudonym;
});
$state.go('app.dashboard');
if (!firebaseUser.emailVerified) {
// firebaseUser.sendEmailVerification();
toastr.info('Your email is NOT verified.', 'Verify email!');
$state.go('login.signin');
}
// $state.go('home');
})
.catch(function(error) {
toastr.error(error.message, error.reason, { timeOut: 10000 });
$scope.user = {};
})
}
};
You should use a Service to store the value and retrieve it whenever you need.
var myApp = angular.module('myApp',[]);
myApp.service('mySingleton', function() {
var username= "test";
return {
username : username
};
});
function MyCtrl($scope, mySingleton) {
$scope.username= mySingleton.username;
}
function MyCtrl2($scope, mySingleton) {
$scope.username= mySingleton.username;
}

Ionic Pubnub chat in Angular: ionic.bundle.js:21157 TypeError: PubNub.publish is not a function

I am creating whatsapp application by using PubNub Api and ionic platform. However, it comes with problem that ionic.bundle.js:21157 TypeError: PubNub.publish is not a function. Below is my code. Can anyone help me?
var chat = angular.module('chat', ['pubnub.angular.service']);
chat.controller('chatController', ['$scope', '$state', '$rootScope',
'$stateParams', 'PubNub', '$http', '$ionicScrollDelegate',
function($scope, $state, $rootScope, $stateParams, PubNub, $http,
$ionicScrollDelegate){
var nickname = $stateParams.nickname;
var channel = $stateParams.channel;
$scope.messageContent = '';
$scope.messages = [];
$scope.goBack = function() {
$state.go('channels',{nickname: nickname, channel: channel});
}
PubNub.init({
publish_key:'',
subscribe_key:'',
ssl: true,
nickname: nickname
});
$scope.sendMessage = function() {
if (!$scope.messageContent ||
$scope.messageContent === '') {
return;
}
PubNub.publish({
channel: channel,
message: {
content: $scope.messageContent,
nickname: nickname
},
callback: function(m) {
console.log(m);
}
});
$scope.messageContent = '';
}
PubNub.ngSubscribe({channel: channel});
$rootScope.$on(PubNub.ngMsgEv(channel), function(event, payload) {
$scope.$apply(function() {
$scope.messages.push(payload.message);
$ionicScrollDelegate.scrollBottom();
console.log(payload.message);
});
});
}]);
The name of the service to inject is Pubnub instead of PubNub.

Pubnub chat in Angular

I'm implementing the pubnub chat in my AngularJS application. I'm following this tutorial
The problem is that if I create a new AngularJS application from scratch the chat works, but if I implement the code in my already existing application I get this error:
Missing Callback pubnub.min.js:1
And I can't see messages that I write and messages that I should receive but I can send them and I can see those messages on the other side of the chat.
Do you know how can I solve this problem?
EDIT: this is the controller for the pubnub chat:
'use strict';
angular.module('myApp.appointments', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
}])
.controller('appointmentsCtrl', ["$rootScope", "$scope", "$http", "$timeout", "$cookies", "URL", "Pubnub", function($rootScope, $scope, $http, $timeout, $cookies, URL, Pubnub) {
$scope.sortType = 'name';
$scope.sortReverse = false;
$scope.sortType_s = 'time';
$scope.filterAppointments = false;
$scope.filterDate = '';
$scope.highlightRow = '';
$scope.$on('$routeChangeSuccess', function() {
var data = {
"token":$cookies.get('userToken'),
"hairdresser_id": $cookies.get('userId')
};
$http.post(URL.url + 'appointments', data).then(function(res){
$scope.app_list = res.data.appointments;
$scope.service_list = res.data.appointment_services;
$scope.customers_list = res.data.customers;
$scope.pending_number = res.data.pending;
});
data = {
"token":$cookies.get('userToken'),
"hairdresser_id": $cookies.get('userId')
};
$http.post(URL.url + 'monthly_earnings', data).then(function(res){
$rootScope.monthly_earnings = res.data.amount;
});
});
// Pubnub implementation
$scope.channel = "messages-channel";
$scope.uuid = _.random(100).toString();
Pubnub.init({
publish_key: MY_KEY,
subscribe_key: SUB_KEY,
ssl: true,
uuid: $scope.uuid
});
$scope.sendMessage = function() {
if (!$scope.messageContent || $scope.messageContent === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
console.log(m);
}
});
$scope.messageContent = '';
}
$scope.messages = [];
Pubnub.subscribe({
channel: $scope.channel,
triggerEvent: ['callback']
});
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function(ngEvent, m) {
$scope.apply(function() {
$scope.messages.push(m)
});
});
}]);
You forgot the s at the end of the triggerEvents statement in the Pubub.subscribe function :
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback']
});
Let me know if it has solved your issue.

AngularFire Authentication with Route Limiting

I'm currently working on my first Angular application. Each hurdle I get over is really helping me with my understanding of how everything in Angular comes together but also programming in general.
Right now, I am experimenting with AngularFire and Firebase as the back end to the application. Further down the line, I will store other data in Firebase, but right now I am focused on getting the User Authentication part down.
Currently, the application is comprised of an index.html page, which loads the navigation HTML elements as a header, and then loads partials within an ng-view element. This keeps the navigation constant and the pages dynamic (much of the content is generated via Angular from various JSON objects). It also includes a login.html that is entirely separate and does not include the navigational elements from the main application, but does use the same controllers and modules as the rest of the application. I've managed to cobble together a working login, which interfaces successfully with Firebase. This can verify existing e-mail/password combinations or register new users. What I really want is for a successful login to redirect to index.html, and if someone tries to access index.html or any of the partials without having signed in, to be redirected to the login.html. I'm not entirely sure how to approach this, though I believe it will have something to do with the router. I'd also like to keep the authentication information attached to a persistent user object so it can be used in controlling the visibility and functionality of navigation options later on.
The Angular code that I am using:
var profileApp = angular.module('profileApp', ['ngRoute', 'firebase']);
profileApp.controller('LoginCtrl', ['$scope', '$rootScope', '$firebaseAuth', function($scope, $rootScope, $firebaseAuth) {
var ref = new Firebase('https://FIREBASEURL.firebaseio.com/');
$rootScope.auth = $firebaseAuth(ref);
$scope.signIn = function () {
$rootScope.auth.$login('password', {
email: $scope.email,
password: $scope.password
}).then(function(user) {
$rootScope.alert.message = '';
}, function(error) {
if (error = 'INVALID_EMAIL') {
console.log('email invalid or not signed up — trying to sign you up!');
$scope.signUp();
} else if (error = 'INVALID_PASSWORD') {
console.log('wrong password!');
} else {
console.log(error);
}
});
}
$scope.signUp = function() {
$rootScope.auth.$createUser($scope.email, $scope.password, function(error, user) {
if (!error) {
$rootScope.alert.message = '';
} else {
$rootScope.alert.class = 'danger';
$rootScope.alert.message = 'The username and password combination you entered is invalid.';
}
});
}
}
]);
profileApp.controller('AlertCtrl', [
'$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.alert = {};
}
]);
profileApp.controller('HistoryCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.historyItems = data;
});
});
profileApp.controller('FaceCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.faceItems = data;
});
});
profileApp.controller('PhysicalCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.physicalItems = data;
});
});
profileApp.controller('MenuCtrl', function ($scope, $http){
$http.get('profile.json').success(function(data) {
$scope.profileItems = data;
});
});
profileApp.controller('ContentCtrl', function ($scope, $http){
$http.get('content.json').success(function(data) {
$scope.contentItems = data;
});
});
profileApp.controller('OrdersCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.ordersItems = data;
});
});
profileApp.controller('MedAdminCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.medadminItems = data;
});
});
profileApp.controller('LabsCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.labItems = data;
});
});
profileApp.controller('VitalsCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.vitalItems = data;
});
});
profileApp.controller('AssessmentCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.asessmentItems = data;
});
});
profileApp.controller('IoCtrl', function ($scope, $http){
$http.get('patient.json').success(function(data) {
$scope.ioItems = data;
});
});
profileApp.config(['$routeProvider', function ($routeProvider) {
__insp.push(["virtualPage"]);
$routeProvider
// Home
.when("/", {
templateUrl: "partials/face.html",
controller: "FaceCtrl"
})
.when("/face", {
templateUrl: "partials/face.html",
controller: "FaceCtrl"
})
// Pages
.when("/medicalHistory", {
templateUrl: "partials/medicalhistory.html",
controller: "HistoryCtrl"
})
.when("/physicalExam", {
templateUrl: "partials/physicalexam.html",
controller: "PhysicalCtrl"
})
.when("/orders", {
templateUrl: "partials/orders.html",
controller: "OrdersCtrl"
})
.when("/medAdmin", {
templateUrl: "partials/medadmin.html",
controller: "MedAdminCtrl"
})
.when("/labs", {
templateUrl: "partials/labs.html",
controller: "LabsCtrl"
})
.when("/vitals", {
templateUrl: "partials/vitals.html",
controller: "VitalsCtrl"
})
.when("/assessment", {
templateUrl: "partials/assessment.html",
controller: "AssessmentCtrl"
})
.when("/io", {
templateUrl: "partials/io.html",
controller: "IoCtrl"
})
//.when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
// else 404
.otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);
Here!, Iv changed the code.... Check this out and let me know if this solves the problem!
To Sign In and Sign Up:
profileApp.controller('LoginCtrl', ['$scope', '$location', '$firebase',
function($scope, $location, $firebase) {
$scope.message = "";
var username = "";
var password = "";
var ref = new Firebase("https://FIREBASEURL.firebaseio.com/");
$scope.signIn = function() {
username = $scope.username;
password = $scope.password;
ref.authWithPassword({
email: username,
password: password
}, function(error, authData) {
if (error) {
switch (error.code) {
case "INVALID_EMAIL":
alert("The specified user account email is invalid.");
break;
case "INVALID_PASSWORD":
alert("The specified user account password is incorrect.");
break;
case "INVALID_USER":
alert("The specified user account does not exist.");
break;
default:
alert("Error logging user in:", error)
}
$scope.message = "Wrong Username/Password;";
} else {
$location.path("/home");
}
}, {
remember: "sessionOnly"
});
};
};
$scope.signUp = function () {
$rootScope.auth.$createUser($scope.email, $scope.password, function (error, user) {
if (!error) {
$rootScope.alert.message = '';
} else {
$rootScope.alert.class = 'danger';
$rootScope.alert.message = 'The username and password combination you entered is invalid.';
}
});
};
]);
To Sign Out:
profileApp.controller('home', ['$scope', '$location', '$firebase',
function($scope, $location, $firebase) {
function authDataCallback(authData) {
if (authData) {
alert("Logged in...");
} else {
$location.path("/login");
alert("Log in to access this page");
}
};
var ref = new Firebase("https://FIREBASEURL.firebaseio.com/");
ref.onAuth(authDataCallback);
$scope.logoutUser = function() {
ref.unauth();
$location.path("/login");
};
// Authentication Code
One more thing! You click the submit button and you will not be navigated to another desired view on correct Username/Password. Here what you will do:
1- After clicking submit button wait for 5-10 seconds.
2- After that click the submit button again. Try this out for now.
Cheers!

Categories