Angular js cannot save cookies instead it throw undefined error - angularjs

hi I try to save in cookies after a web response. Here is my code
angular.module('myApp').controller('SignInController',['WebService',function(WebService, $cookies){
this.formData = {};
this.signIn = function(formData){
WebService.login(formData).then(function successCallback(data){
//console.log("Success callback:"+JSON.stringify(data));
var response = data.data;
var message = response['message'];
if (message == 'Success') {
$cookies.put("id", response['id']);
$cookies.put("number", response['number']);
}else{
}
console.log('Message:'+message+" id:"+ $cookies.get('id'));
},function errorCallback(error){
console.log("Error"+JSON.stringify(error));
});
this.formData = {};
};
}]);
i have included ngCookies as module while creating main angular module. What I'm doing wrong here? Anyone show me correct way. Thank you.

array containing all string of all arguments is good approach to handle dependency injection (DI) after your code is minified.
angularJs use Named_parameter in DI, you can understand how DI works by this blog post.
when you minified you angularJs file, ($http, $scope) converted to (a, b) and DI can't understand them.
$inject is my recommended way to handle this situation. its looks clean. (personal opinion, can be vary).
and try to write code which easily maintainable.
var app = angular.module('myApp', []);
SignInController.$inject = ['WebService', '$cookies'];
app.controller('SignInCtrl', SignInController);
function SignInController(WebService, $cookies){
this.formData = {};
this.signIn = signIn;
function signIn(formData) {
WebService.login(formData)
.then(successCallback, errorCallback);
function errorCallback(error){
console.log("Error"+JSON.stringify(error));
}
function successCallback(data){
var response = data.data;
var message = response['message'];
if (message == 'Success') {
$cookies.put("id", response['id']);
$cookies.put("number", response['number']);
}
}
this.formData = {};
};

Related

Reference Error in API function call using AngularJS

formApp.controller('load', function ($scope, ApiCall, $window, $http) {
$window.onload = function () {
alert("the page loaded and will now call the function");
ApiCall.GetApiCall("signOn", "GetSingleSignOn").success(function (data) {
alert("successful call to singleSignOn, GetSingleSignOn");
var data = $.parseJSON(JSON.parse(data));
$scope.apiGetInfo = data;
alert("successful call to singleSignOn, GetSingleSignOn");
alert(data);
});
};
This code works fine up to the var data- $.parseJson(JSON.parse(data));
I looked at some examples of how to do this in the Controller online and they all looked this way with $.parseJSON(JSON.parse(data)).
It gives me: ReferenceError: $ is not defined
Not sure why as every example I looked at to call an API Controller in Angular showed this way.
You don't need the $.parseJSON. remove it and leave the JSON.parse intact:
var data = JSON.parse(data);
If you want to use JQuery ($) you have to import the script.
UPDATE:
if you want to redirect to an URL you can use $window:
$window.location.href = 'http://www.google.com';

Firebase loading $scope view enter doesn't load

I have a loading problem in Firebase. I want to display a list of images when I open the view but nothing happens till i go back ( there is a flash and i can see my photo list). It's working but not displaying in the opening.
What am i missing please ?
There is the beginning of my Controller view:
'Use Strict';
angular.module('App').controller('valider_photosController', function($scope, $state, $localStorage, Popup, Firebase, $firebaseObject, $ionicHistory, $ionicPopup, $ionicModal, $cordovaCamera) {
$scope.imagestab = [];
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');
ref_logements.child(id_logement).child('images').on('child_added', added);
function added(idxSnap, prevId){
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
console.log('La valeur'+datasnap.key+'donne '+datasnap.val());
});
};
});
Since firebase works with asynchronous calls, by the time firebase responds with your data the angular cycle had already finished and you won't have your scope updated. You can force it by using $scope.$apply();.
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
$scope.$apply();
});
There is a tool that integrates angular and firebase in a way that you won't have to be concerned with things such as applying the scope. Its called angularfire. I totally recommend you to start using it in your application.
With angularfire you can get your data simply using
$scope.bidule = $firebaseObject(ref_images.child(idxSnap.key));
or
$scope.images = $firebaseArray(firebase.database().ref('images'));
I created a Factory
.factory('Firebase', function ($firebaseArray, $firebaseObject) {
var ref = firebase.database().ref();
return {
all: function (section) {
var data = $firebaseArray(ref.child(section));
return data;
},
getById: function (section, id) {
var data = $firebaseObject(ref.child(section).child(id));
return data;
},
get: function (section, field, value) {
var data = $firebaseArray(ref.child(section).orderByChild(field).equalTo(value));
return data;
}
};
})
And then in my controller, i replaced like you said :
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');
ref_logements.child(index2).child('images').on('child_added', added);
function added(idxSnap, prevId) {
var monimage = Firebase.getById('images', idxSnap.key);
$scope.imagestab.push(monimage);
};
And it Works like a charm ! Thank you again :)

How to chain promises returned from Services in AngularJS

According to best practices I have created a service for all different chunks of API call and call the file as api.js;
Here is one example.
api.service('Auth', function(Config, $http, $q, $state) {
this.login = function(jsonToSend) {
return $http.post(Config.apiurl + '/user/auth/login', jsonToSend)
.then(function(response) {
return response.data;
}, function(error) {
return $q.reject(error.data);
});
};
// Api function for signing the user up
this.signup = function(jsonToSend) {
return $http.post(Config.apiurl + '/user/auth/signup', jsonToSend)
.then(function(response) {
return response.data;
}, function(response) {
return $q.reject(response.data);
});
};
});
Now in my loginController.js I inject this service with other services. Now what I want to is.
Auth.Login()
.User.getUser()
.User.getCart()
.Item.getProduct()
My kiddish attempt. I know it's wrong but the community asks you to show what you did.
var q = $q.defer() //intialize
Auth.login().then(function(response){
//some manipulation and store stuff in data
$q.resolve(data);
})
.then(function(data){
})
I want to chain them like this. I know the representation is wrong, but I hope you get the idea of what I am trying to do here.
I have another option of doing this via waterfall method of async.js/ underscore.js but I want to improve my knowledge on promises and hence would like to know if this approach is possible.
Thanks.
You can to save the promises to vars like this:
var loginPromise = Auth.login();
var userPromise = User.getUser();
var chartPromise = User.getCart();
var productPromise = Item.getProduct();
Then you can wait for all promises to resolve and do something with the results like this:
$q.all([loginPromise, userPromise , chartPromise , productPromise]).then(function(data){
/* You can Access each promise data with the index of the order you put them into $q.all(..
* data[0], data[1], data[2], data[3]
*/
});

Can not figure out how to store $rootScope in angular.bootstrap

I'm trying to call a web service in AngularJS bootstrap method such that when my controller is finally executed, it has the necessary information to bring up the correct page. The problem with the code below is that of course $rootScope is not defined in my $http.post(..).then(...
My response is coming back with the data I want and the MultiHome Controller would work if $rootScope were set at the point. How can I access $rootScope in my angular document ready method or is there a better way to do this?
angular.module('baseApp')
.controller('MultihomeController', MultihomeController);
function MultihomeController($state, $rootScope) {
if ($rootScope.codeCampType === 'svcc') {
$state.transitionTo('svcc.home');
} else if ($rootScope.codeCampType === 'conf') {
$state.transitionTo('conf.home');
} else if ($rootScope.codeCampType === 'angu') {
$state.transitionTo('angu.home');
}
}
MultihomeController.$inject = ['$state', '$rootScope'];
angular.element(document).ready(function () {
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
$http.post('/rpc/Account/IsLoggedIn').then(function (response) {
$rootScope.codeCampType = response.data
angular.bootstrap(document, ['baseApp']);
}, function (errorResponse) {
// Handle error case
});
});
$scope (and $rootScope for that matter) is suppose to act as the glue between your controllers and views. I wouldn't use it to store application type information such as user, identity or security. For that I'd use the constant method or a factory (if you need to encapsulate more logic).
Example using constant:
var app = angular.module('myApp',[]);
app.controller('MainCtrl', ['$scope','user',
function ($scope, user) {
$scope.user = user;
}]);
angular.element(document).ready(function () {
var user = {};
user.codeCampType = "svcc";
app.constant('user', user);
angular.bootstrap(document, ['myApp']);
});
Note Because we're bootstrapping the app, you'll need to get rid of the ng-app directive on your view.
Here's a working fiddle
You could set it in a run() block that will get executed during bootstrapping:
baseApp.run(function($rootScope) {
$rootScope.codeCampType = response.data;
});
angular.bootstrap(document, ['baseApp']);
I don't think you can use the injector because the scope isn't created before bootstrapping. A config() block might work as well that would let you inject the data where you needed it.

AngularJS - Function Expected or Object is not a Function

New to AngularJS and I guess I don't understand how to call one Promise method from another with the same factory. Every time my code gets to the $http.get within processPerson, I get a Function Expected error in IE, or an Object is not a Function error in Chrome. I've tried reorganizing code many times, multiple factories, etc, and generally get the same error. The only time I can get this to work is if I combine the functions where the processPerson function is embedded within the success of the getPersonnel.
Code:
(function(){
var app = angular.module('hrSite', ['personnel']);
app.controller('PersonnelController', function($scope, personnelFactory){
var personnelPromise = personnelFactory.getPersonnel();
personnelPromise.then(function(personnel){
var perDefs = new Array();
$.each(personnel.data.value, function( i, person ){
var perDef = personnelFactory.processPerson(person);
perDefs.push(perDef);
});
$q.all(perDefs).then(function(){
$scope.personnel = personnel.data.value;
});
});
});
})();
(function(){
var personnelModule = angular.module('personnel', []);
personnelModule.factory('personnelFactory', function($http, $q) {
var getPersonnel = function(){
return $http.get("/sites/Development/_api/web/lists/getbytitle('Personnel')/items");
};
var processPerson = function(person){
var deferred = $q.defer();
$http.get("/sites/Development/_api/web/lists/getbytitle('Personnel Skills')/items?$select=*,Skill/Id,Skill/Title&$filter=PersonId eq '"+person.Id+"'&$expand=Skill").then(function(skills){
person.Skills = skills.data.value;
person.SkillsId = [];
$.each(skills.data.value, function( j, skill ){
person.SkillsId.push(skill.Id);
});
deferred.resolve();
});
return deferred.promise();
};
return {getPersonnel: getPersonnel,
processPerson: processPerson}
});
})();
Nevermind - I figured it out. I was migrating code from a jQuery project and in jQuery, you return a promise like this:
return deferred.promise();
Since Angular has its own deferred feature, $q, I began using that, without realizing that the notation to return a promise was slightly different:
return deferred.promise;
No () in that, which was really screwing things up. Now everything seems to be working fine.

Resources