I'm using ng-file-upload for uploading image in my project but
whenever I implement localStorage using AuthFactory.setToken({token: "secret_token", expires: 'time'}); ng-file-upload fails to send image to server. It does not conflict with AuthFactory.setUser(user_obj)
.factory('AuthFactory', ['LSFactory', function(LSFactory) {
var userKey = 'user';
var tokenKey = 'token';
var AuthAPI = {
isLoggedIn: function() {
return this.getUser() === null ? false : true;
},
getUser: function() {
return LSFactory.get(userKey);
},
setUser: function(user) {
return LSFactory.set(userKey, user);
},
getToken: function() {
return LSFactory.get(tokenKey);
},
setToken: function(token) {
return LSFactory.set(tokenKey, token);
},
deleteAuth: function() {
LSFactory.delete(userKey);
LSFactory.delete(tokenKey);
}
};
return AuthAPI;
}])
.factory('LSFactory', [function() {
var LSAPI = {
clear: function() {
return localStorage.clear();
},
get: function(key) {
return JSON.parse(localStorage.getItem(key));
},
set: function(key, data) {
return localStorage.setItem(key, JSON.stringify(data));
},
delete: function(key) {
return localStorage.removeItem(key);
},
getAll: function() {
var books = [];
var items = Object.keys(localStorage);
for (var i = 0; i < items.length; i++) {
if (items[i] !== 'user' || items[i] != 'token') {
books.push(JSON.parse(localStorage[items[i]]));
}
}
return books;
}
};
return LSAPI;
}])
Related
User.find({ refUser: req.params.userName }).then(function (users) {
var network_users = [];
network_users.push(users);
users.forEach(function (u) {
network_users.push(User.find({ refUser: u.toObject().userName }));
})
return Promise.all(network_users);
I have 4 users, I expected receive a json with all of childrens but I only received the first and the children of this first.
Someone can help me with this loop? Please! Thanks so much!!!!
function asyncLoop(iterations, func, callback, foo) {
var done = false;
var loop = {
next: function () {
if (done) {
return;
}
if (iterations) {
func(loop);
} else {
done = true;
if (callback) callback(foo);
}
},
isEnd: function () {
return done;
},
refresh: function (it) {
iterations = it;
},
break: function () {
done = true;
callback();
}
};
loop.next();
return loop;
}
function bfs(userName, callback) {
userName = String(userName);
var q = [], res = [];
User.findOne({ "refUser" : userName }).lean().exec(function (err, root) {
root.depth = 0;
q.push(root);
asyncLoop(q.length, function (loop) {
res.push(q[0]);
User.find({ "refUser" : q[0].userName }).lean().exec(function (err, new_nodes) {
if (err) console.log(err);
else {
var d = q[0].depth;
q.shift();
loop.refresh(new_nodes.length + q.length);
if (new_nodes.length > 0) {
new_nodes.forEach(function (new_node) {
new_node.depth = d + 1;
q.push(new_node);
});
}
loop.next();
}
});
}, function () { callback(res) });
});
}
Finishing:
bfs(req.params.userName,function(callback){
res.send(callback)
})
Trying to code in Javascript on AWS Lambda. The code is meant for Alexa to go to a URL and stream the audio on there using the AudioPlayer.
Can't figure out what I am missing in this code or what is wrong with it and I get this error through the log.
Code:
'use strict';
var alexa = require('alexa-sdk');
var APP_ID = "amzn1.ask.skill.b5c95058-7134-4044-9e77-a4279e0adaf7";
var PAUSE_MESSAGE = "paused!";
var RESUME_MESSAGE = "resumed!";
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
var handlers = {
'play': function(audioURL, offsetInMilliseconds) {
var response = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [{
type: "AudioPlayer.Play",
playBehavior: "REPLACE_ALL",
audioItem: {
stream: {
url: 'https://feeds.soundcloud.com/stream/275202399-amazon-web-services-306355661-amazon-web-services.mp3',
offsetInMilliseconds: 10
}
}
}]
}
}
this.context.succeed(response);
},
'AMAZON.PauseIntent': function() {
this.emit(':tell', PAUSE_MESSAGE);
},
'AMAZON.ResumeIntent': function() {
this.emit(':tell', RESUME_MESSAGE);
}
};
I ended up changing my code.
Code:
var lastPlayedByUser = {};
var streamURL = "http://cpdc101-lh.akamaihd.net/i/ISNCPDCMB1_1#314337/master.m3u8";
exports.handler = function(event, context) {
var player = new Player(event, context);
player.handle();
};
var Player = function (event, context) {
this.event = event;
this.context = context;
};
Player.prototype.handle = function () {
var requestType = this.event.request.type;
var userId = this.event.context ? this.event.context.System.user.userId : this.event.session.user.userId;
if (requestType === "LaunchRequest") {
this.play(streamURL, 0);
} else if (requestType === "IntentRequest") {
var intent = this.event.request.intent;
if (intent.name === "Play") {
this.play(streamURL, 0);
} else if (intent.name === "AMAZON.PauseIntent") {
this.stop();
} else if (intent.name === "AMAZON.ResumeIntent") {
var lastPlayed = this.loadLastPlayed(userId);
var offsetInMilliseconds = 0;
if (lastPlayed !== null) {
offsetInMilliseconds = lastPlayed.request.offsetInMilliseconds;
}
this.play(streamURL, offsetInMilliseconds);
}
} else if (requestType === "AudioPlayer.PlaybackStopped") {
this.saveLastPlayed(userId, this.event);
this.context.succeed(true);
}
};
Player.prototype.play = function (audioURL, offsetInMilliseconds) {
var response = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [
{
type: "AudioPlayer.Play",
playBehavior: "REPLACE_ALL",
audioItem: {
stream: {
url: audioURL,
token: "0",
expectedPreviousToken: null,
offsetInMilliseconds: offsetInMilliseconds
}
}
}
]
}
};
this.context.succeed(response);
};
Player.prototype.stop = function () {
var response = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [
{
type: "AudioPlayer.Stop"
}
]
}
};
this.context.succeed(response);
};
Player.prototype.saveLastPlayed = function (userId, lastPlayed) {
lastPlayedByUser[userId] = lastPlayed;
};
Player.prototype.loadLastPlayed = function (userId) {
var lastPlayed = null;
if (userId in lastPlayedByUser) {
lastPlayed = lastPlayedByUser[userId];
}
return lastPlayed;
};
I have a weird problem.. when I am loading my details page, the error part gets executed first in the controller.
Though the service myService gets executed and it does return value, in the controller error is executed and I am not getting my message details.
I have put an alert in service before and jsonObj is valid.
controller:
url = 'http://' + add + ':8080/user/site.cgi';
data = {
ACTION : "list",
STATS : "no"
};
myService.getdata(url, data)
.then(function(data, status, headers, config) {
$timeout(function(){
if (data.body.response.status == "OK") {
if (data.body.response.msg.id) {
service2.seturl(data.body.response.msg.id, username, add);
messg.push(data.body.response.msg);
} else
angular.forEach(data.body.response.msg, function(value, key) {
service2.seturl(value.id, username, add);
messg.push(value);
})
$rootScope.messg = messg;
} else {
errorMessage = data.body.response.errmsg;
alert(errorMessage);
}
}, 5000);
}, function(error, status, headers, config) {
alert("Check network connection.."); //Coming here without fulfilling promise.
});
}
services:
.service('myService', function($http, $q, $httpParamSerializerJQLike) {
return {
getdata: function(url, data) {
var postData = data;
return $http({
method : 'POST',
url : url,
data : $httpParamSerializerJQLike(postData)
}).then(function(response, status, headers, config) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert(jsonObj); //I am getting this alert just fine.
return jsonObj; //It does return the object.
} else {
return $q.reject(jsonObj);
}
}, function(response, status, headers, config) {
return $q.reject(response.data);
});
}
}
})
.factory('service2', function() {
var urls = [{ }];
return {
all: function() {
return urls;
},
geturl: function(id) {
for (var i = 0; i < urls.length; i++) {
if (urls[i].id === parseInt(id)) {
return urls[i];
}
}
return null;
},
seturl: function(id, admin, add) {
for (var i = 0; i < urls.length; i++) {
if (urls[i].id === parseInt(id)) {
return null;
}
}
var idInt = parseInt(id);
var createurl = 'http://' + add + ':8080/user/det.cgi';
var postData = {
ACTION : “add”,
LOGIN : admin
};
var url = {
id: idInt,
url: createurl,
data: postData
}
urls.push(url);
return null;
}
};
})
Try this , return a deferred promise
.service('myService', function($http, $q, $httpParamSerializerJQLike) {
return {
getdata: function(url, data) {
var deferred = $q.defer();
var postData = data;
$http({
method : 'POST',
url : url,
data : $httpParamSerializerJQLike(postData)
}).then(function(response, status, headers, config) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert(jsonObj);
deferred.resolve(jsonObj);
} else {
deferred.reject(jsonObj);
}
}, function(response, status, headers, config) {
deferred.reject(response.data);
});
return deferred.promise;
}
}
})
The problem I have is that on page load the response from the API takes a while and my view (scope) is empty. But when I switch view back and forth the groups-view (scope) is updated with the object which was loaded from the API on page load.
I want to be able to load all my data and have it available in all views at all time and for it to dynamically update the first view (scope) on page load when the data becomes available.
I guess this is possible, but what am I missing?
My service:
angular.module('myApp.services', [])
.service('groups', function ($http) {
var groups = [];
// Load the data once from the API
if(!groups.length) {
$http.get('/api/groups')
.then(
function(response) {
groups = response.data;
}
);
}
return {
// For update if new data is available
setData: function(arr) {
groups = arr;
},
// Return all groups
getAll: function () {
return groups;
},
// Get a given group name
getNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].name;
}
}
return null;
},
// Get a given group short name
getShortNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].short_name;
}
}
return null;
},
getTeamsById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].team_ids;
}
}
return null;
}
};
});
My controller:
function GroupsOverviewCtrl($scope, groups) {
// Populate the scope with data
$scope.groups = groups.getAll();
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];
The "Angular way" of dealing with async operations is promises instead of callbacks.
This is what it might look like:
.factory('groups', function ($http, $q) {
var groups = [],
return {
setData: function(arr) {
groups = arr;
},
getAll: function () {
if(groups.length) {
return $q.when(groups);
} else {
return $http.get('/api/groups').then(function (response) {
groups = response.data;
return groups;
});
}
},
getNameById: function (id) {...},
getShortNameById: function (id) {...},
getTeamsById: function (id) {...}
};
});
function GroupsOverviewCtrl($scope, groups) {
groups.getAll().then(function (data) {
$scope.groups = data;
});
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];
Ok, so I think I've fixed it... getting late here and my brain is shutting down.
The answer was to use a callback (as always with http request).
The service:
angular.module('myApp.services', [])
.factory('groups', function ($http) {
var groups = [],
groupsObj = {
setData: function(arr) {
groups = arr;
},
getAll: function () {
return groups;
},
getNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].name;
}
}
return null;
},
getShortNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].short_name;
}
}
return null;
},
getTeamsById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].team_ids;
}
}
return null;
}
};
return {
get: function(callback) {
if(!groups.length) {
$http.get('/api/groups')
.then(
function(response) {
groups = response.data;
callback(groupsObj);
}
);
} else {
callback(groupsObj);
}
}
};
});
The controller:
function GroupsOverviewCtrl($scope, groups) {
groups.get(function(groupsObj) {
$scope.groups = groupsObj.getAll();
});
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];
So when I try and run my jasmine tests, i get this error on every test:
TypeError: Property '$' of object [object Object] is not a function
at jasmine.Fixtures.cleanUp (http://localhost:8234/src/target/test-classes/frontend/thirdParty/js/com/github/velesin/jasmine-jquery/0.0.0/jasmine-jquery-0.0.0.js:117:3)
at null.<anonymous> (http://localhost:8234/src/target/test-classes/frontend/thirdParty/js/com/github/velesin/jasmine-jquery/0.0.0/jasmine-jquery-0.0.0.js:548:25)
at jasmine.Block.execute (http://localhost:8234/?:1152:19)
at jasmine.Queue.next_ (http://localhost:8234/?:2184:33)
at jasmine.Queue.start (http://localhost:8234/?:2137:10)
at jasmine.Spec.execute (http://localhost:8234/?:2464:16)
at jasmine.Queue.next_ (http://localhost:8234/?:2184:33)
at onComplete (http://localhost:8234/?:2180:20)
at jasmine.Spec.finish (http://localhost:8234/?:2438:7)
at null.onComplete (http://localhost:8234/?:2465:12)
I've seen the various posts and SO's about jquery running in noConflict mode and that I need to use jQuery throughout my code, but the code I'm testing doesnt have any $'s in it.
code:
$provide.factory('corsHttpInterceptor', ['$q', '$window', '$exceptionHandler', '$rootScope', 'jq360', function($q, $window, $exceptionHandler, $rootScope, jq360){
var corsHttpInterceptor,
ieCorsTimeoutTime;
function fixConfigForXdr(config)
{
if (config.method.toUpperCase() === "PUT")
{
config.method = "POST";
if (angular.isDefined(config.params))
{
config.params._method = "put";
}
else
{
config.params = {_method: "put"};
}
}
else if (config.method.toUpperCase() === "DELETE")
{
config.method = "GET";
if (angular.isDefined(config.params))
{
config.params._method = "delete";
}
else
{
config.params = {_method: "delete"};
}
}
}
function getResponseDataForXdr(xdr)
{
var responseData = xdr.responseText;
if ("application/json" === xdr.contentType)
{
responseData = angular.fromJson(responseData);
}
return responseData;
}
function getIEUrl(config)
{
var url = config.url;
if (angular.isDefined(config.params) && !angular.equals(config.params, {}))
{
if (-1 === url.indexOf("?"))
{
url += "?";
}
else
{
url += "&";
}
url += jq360.param(config.params);
}
return url;
}
corsHttpInterceptor = {
request: function(config){
var deferred,
promise,
xdr;
if ('withCredentials' in new $window.XMLHttpRequest())
{
return config;
}
else if (angular.isDefined($window.XDomainRequest))
{
config.method = angular.uppercase(config.method);
deferred = $q.defer();
//this promise already has the then function so don't need to add it
promise = deferred.promise;
try
{
xdr = new $window.XDomainRequest();
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "new XDomainRequest()");
}
try
{
fixConfigForXdr(config);
xdr.open(config.method, getIEUrl(config));
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.open");
}
xdr.onprogress = function() {}; //http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e/
xdr.ontimeout = function() {};
xdr.onload = function() {
try
{
var responseData = getResponseDataForXdr(xdr);
deferred.resolve({data: responseData, status: 200});
$rootScope.$apply();
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.onload");
}
};
xdr.onerror = function() {
try
{
deferred.reject({data: "", status: 500});
$rootScope.$apply();
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.onerror");
}
};
xdr.timeout = 0;
$window.setTimeout(function() { //IE CORS requests are inconsistent without the setTimeout. Reference: http://stackoverflow.com/questions/5250256/inconsistent-ajax-xdr-response-from-ie
try
{
if ("GET" === config.method)
{
xdr.send();
}
else
{
xdr.send(angular.toJson(config.data));
}
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.send");
}
}, ieCorsTimeoutTime);//TEMPORARY way to dynamically set the timeout time for IE CORS requests
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status);
});
return promise;
};
return promise;
}
else
{
throw new Error("Browser doesn't support needed functionality.");
}
},
response: function(response){
return response;
},
responseError: function(rejection){
return $q.reject(rejection);
},
ieCorsTimeoutTime: ieCorsTimeoutTime
};
return corsHttpInterceptor;
}]);
test:
'use strict';
var mockAppbaseModule;
describe('appbaseWithCors', function(){
mockAppbaseModule = angular.module("appbase", []);
beforeEach(module(function($provide, $exceptionHandlerProvider) {
$provide.provider('jq360', function() {
this.$get = function() {
return $;
};
});
$exceptionHandlerProvider.mode('log');
}));
beforeEach(module('appbaseWithCors'));
describe("corsHttpInterceptor", function () {
var successCallback = null;
var errorCallback = null;
var successResponse = {foo: 'blah'};
var errorResponse = {errorCode: 123, appServer: 1};
beforeEach(inject(function() {
successCallback = jasmine.createSpy("successCallback");
errorCallback = jasmine.createSpy("errorCallback");
}));
var appStatus;
describe("Standard CORS", function () {
beforeEach(inject(function($window){
appStatus = {
appBaseUrl : "",
appServer: 1,
token: "TEST_TOKEN"
};
spyOn($window, "XMLHttpRequest").andReturn({withCredentials: 'foo'});
}));
it ("should call the error function when there is an error code in the response data", inject(function($http, $httpBackend) {
$httpBackend.expectGET("TEST_URL").respond(403, errorResponse);
var config = {method: "get", url:"TEST_URL"};
$http(config).success(successCallback).error(errorCallback).then(successCallback, errorCallback);
$httpBackend.flush();
expect(successCallback).not.toHaveBeenCalled();
expect(errorCallback).toHaveBeenCalledWith({data: errorResponse, status: 403, headers: jasmine.any(Function), config: jasmine.any(Object)});
}));
}));
}));
}));