AngularJS $location only works second time after WebSocket call - javascript

In my AngularJS application I'm using WebSocket to connect the application and the API.
My problem is that after making a handshake I want to reroute the user to a new view. This should happen automatic after the call succeeded, this doesn't happen, however if I run the function again it works fine, how can this be?
Error:
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Controller:
...
$scope.signIn = function(){
if($scope.loginForm.$valid){
socketService.handshake($scope.login.username, $scope.login.password, function(response){
if(response.payload.success){
$scope.user = $scope.login;
$scope.user.isLoggedIn = true;
$scope.user = sharedProperties.setUser($scope.user);
$scope.login = {};
$location.path('view/' + sharedProperties.getConfig().views[0].route);
} else {
console.log('Error : Login failed');
}
});
}
};
...
SocketService:
...
var service = {},
socket;
service.handshake = function(username, password, callback){
handshake(username, password, function(response){
callback(response);
});
};
function handshake(username, password, callback){
var jsonObject = {
'agmt': '00001',
'usr': username,
'pwd': password,
"request": 'INIT'
};
socket = new WebSocket(config.socketAddress);
socket.onopen = function () {
console.log("Server is on!");
console.log('json', jsonObject);
socket.send(JSON.stringify(jsonObject));
};
socket.onmessage = function (response) {
console.log('\n' + new Date().toUTCString() + '\nServer responded');
console.log('handshake data : ', response);
callback(JSON.parse(response.data));
};
};
...

Related

Error promise after publish data to MQTT broker in My Alexa Lambda node js

I have problem with my Lambda, actually in promise nodejs. I have wrote code like this in my Lambda:
'use strict'
const Alexa = require('alexa-sdk');
const mqtt = require('mqtt');
const APP_ID = undefined;
const WELCOME_MESSAGE = 'Welcome to the lamp control mode';
const WELCOME_REPROMT = 'If you new please say help'
const HELP_MESSAGE = 'In this skill you can controlling lamp to turn off or on, dim the lamp, change the lamp color and schedule the lamp';
const STOP_MESSAGE = 'Thanks for using this skill, Goodbye!';
const OFF_RESPONSE = 'Turning off the lamp';
const ON_RESPONSE = 'Turning on the lamp';
const DIM_RESPONSE = 'Dimming the lamp';
const CHANGE_RESPONSE = 'Changing the lamp color';
const AFTER_RESPONSE = 'Wanna control something again ?';
const handlers = {
'LaunchRequest': function () {
this.emit(':ask', WELCOME_MESSAGE, WELCOME_REPROMT);
},
'OnOffIntent' : function () {
var status = this.event.request.intent.slots.status.value;
var location = this.event.request.intent.slots.location.value;
console.log(status);
console.log(location);
if (status == 'on') {
// Promise Start
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
// Promise END
// this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
} else if (status == 'off') {
this.emit(':ask', OFF_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
}
},
'DimIntent' : function () {
// to do here
},
'ChangeColorIntent' : function () {
// to do here
},
'ShceduleIntent' : function () {
// to do here
},
'AMAZON.HelpIntent': function () {
this.emit(':ask', HELP_MESSAGE, 'Wanna control something ?');
},
'AMAZON.StopIntent': function () {
this.emit(':tell', STOP_MESSAGE);
}
};
exports.handler = function (event, context, callback) {
const alexa = Alexa.handler(event, context, callback);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
}
I test my code with Service Simulator in Alexa Developer and get this result :
Result Image
So I checked output in Lambda and I got this error report :
Error in Lamda
Can anyone please help me? I have no idea with this because this is my first trial :)
The crux of your error seems to be this specific line in the log:
Cannot read property 'emit' of undefined
And after following the flow of your program, it's likely ocurring here:
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
// It's probably ocurring in this line below
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
)
The log is saying that you tried using this, it's undefined and doesn't have an emit property. Thats ocurring because of how this works in Js. You could workaround this problem by saving a reference to this
var that = this;
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
that.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
I would also recommend reading up a bit on "How 'this' works in Javascript"
MDN
Stack Overflow - "how does 'this' work"

$authWithPassword is not a function in AngularFire 2.x

I've seen posts about this problem before, but they're either outdated or offer a solution very similar to my setup.
Basically, I have two functions in my controller: authCtrl.login and authCtrl.register. The register's call to Auth.$createUserWithEmailAndPassword() works fine, but the login's call to Auth.$authWithPassword() does not, as I'm getting a "..is not a function" error. Can't for the life of me figure out what is wrong here.
Here's my setup:
auth.service.js:
angular.module('angularfireSlackApp')
.factory('Auth', function($firebaseAuth, $firebaseObject){
var auth = $firebaseAuth();
return auth;
});
auth.controller.js:
angular.module('angularfireSlackApp')
.controller('AuthCtrl', function(Auth, $state){
var authCtrl = this;
authCtrl.user = {
email: '',
password: ''
};
authCtrl.login = function() {
// Why is this not a function
Auth.$authWithPassword(authCtrl.user)
.then(function (auth){
$state.go('home');
}, function (error){
authCtrl.error = error;
});
}
authCtrl.register = function() {
Auth.$createUserWithEmailAndPassword(authCtrl.user.email, authCtrl.user.password)
.then(function (user){
authCtrl.login();
}, function (error){
authCtrl.error = error;
});
}
});
try $signInWithEmailAndPassword
See documentation:
https://github.com/firebase/angularfire/blob/master/docs/reference.md#signinwithemailandpasswordemail-password
Maybe a more complete answer building on what Aaron Saunders answered using angularjs and angularfire:
var auth = $firebaseAuth();
$scope.loginUser = function (email, password) {
auth.$signInWithEmailAndPassword(email, password).then(function(firebaseUser) {
console.log("User Logged in successfully with uid: " + firebaseUser.uid);
}).catch(function(error) {
console.log("An Authentication error occurred: " + error);
});
};

unsupported_grant_type error in angularJS and web API

I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData)
{
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; //is not working
//var data = { username: loginData.userName, password: loginData.password, grant_type: "password" }; // I try this and is not working too
//data = $.param(data);
// how should I format my data for the web API to understand
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }
I made google search but still no solution; how can I resolve this issue?
thanks in advance!!

ParseJS, AngularJS user registration error

I am using AngularJS to create a user profile registration with a Parse Backend. However, on my console I am getting an error saying Parse is not defined. How would I be able to make it work and insert a new user into the database?
Below is my code:
.controller('reg',['$scope',function($scope, $state, $rootScope){
$scope.signUp = function() {
var user = new Parse.User();
user.set("email", $scope.user.email);
user.set("password", $scope.user.password);
user.set("firstname", $scope.user.firstname);
user.set("lastname", $scope.user.lastname);
user.signUp(null, {
success: function(user) {
$rootScope.user = user;
$state.go('home');
},
error: function(user, error) {
alert("error here");
}
});
};
}])

Parse Cloud Code beforeSave not running on update

I have defined a Parse Cloud Code function for beforeSave below.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey();
var publicACL = new Parse.ACL();
publicACL.setPublicReadAccess(true);
publicACL.setPublicWriteAccess(true);
request.object.setACL(publicACL);
response.success();
});
This code runs correctly whenever I save a new Parse.User. However, when I try to update a pre-existing Parse.User, the code does not execute. Any thoughts? Below is the code I am using to update my user.
function updateStudentTypes(id, studentType, chkBox) {
var query = new Parse.Query(Parse.User);
query.get(id, {
success: function(user) {
var typeList = user.get("studentType");
if(!chkBox.checked)
typeList = removeStudentType(typeList, studentType);
else
typeList = addStudentType(typeList, studentType);
user.set("studentType", typeList);
user.save(null, {
success: function(user) {
//alert('New object created with objectId: ' + user.id);
},
error: function(user, error) {
alert('Failed to update user: ' + error.message);
}
});
},
error: function(object, error) {
alert("Error querying user: " + error);
}
});
}
Add this to the beginning of your updateStudent method:
Parse.Cloud.useMasterKey();
Edit: I thought your code was cloud code, not client side javascript.

Categories

Resources