Parse/AngularJS - Input data with user id - javascript

I'm working on a Parse App with AngularJS, and reworking a controller to point to the logged in user when posting. On my database table, I've set a column "author" to point to the users. I made a separate service.js file which I call with Squeeg. When I click create, it does not input the data with the user.id. It works fine without it. How would I fix this to ensure that the user objectId is a part of the data is added to the database?
$scope.create=function(){
var user = Parse.User.current();
console.log(user.id);
Squeeg.create({ author:user.id, eventname:$scope.events.title, eventDescription:$scope.events.description}).success(function(data){
alert("done");
});
}

Since I need 50 reputation to comment, this needs to be asked here, have you accessed authfactory/authserverice to get the current user from there? Assuming you have login?
Then in authFactory you could have something like this.
app.factory('authFactory', ['$http', '$window', function ($http, $window) {
var authFactory = {};
authFactory.logIn = function (user) {
return $http.post('/login', user).success(function (data) {
authFactory.saveToken(data.token);
});
};
authFactory.saveToken = function (token) {
$window.localStorage['appToken'] = token;
};
authFactory.getToken = function () {
return $window.localStorage['appToken'];
};
authFactory.logOut = function () {
$window.localStorage.removeItem('appToken');
};
authFactory.currentUser = function () {
if(authFactory.isLoggedIn()){
var token = authFactory.getToken();
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.username; // or return payload.id ..... / return payload
}
};
authFactory.isLoggedIn = function () {
var token = authFactory.getToken();
if(token){
var payload = JSON.parse($window.atob( token.split('.')[1]) );
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
return authFactory;
}]);
Then all you need to do is binding it with your controller to access it.
app.controller('AnyCtrl', ['$scope', 'authFactory',
function ($scope, authFactory) {
$scope.currentUser = authFactory.currentUser;
}
]);

Related

angular get and set atributes via service

i can't find a solution to this, basicly everytime i do a login, i want to store the user that i get from the node end point in the service, after that in my main Controller i should get the name of the user, but that never happen, dunno why
here is the code:
app.controller('MainCtrl', function ($scope, $state,$location,$http,user) {
$scope.user = {
nome: user.getProperty()
};
$scope.showRegister = function () {
$state.go('register');
}
$scope.showLogin = function () {
$state.go('login');
}
});
app.controller('loginController', function ($scope, $http, $state,user) {
$scope.login = function () {
var data = {};
data.password = $scope.loja.password;
data.email = $scope.loja.email;
$http.post('http://localhost:8080/login/',data)
.success(function (data) {
console.log(data);
user.setProperty(data.nome);
$state.go('home');
})
.error(function (statusText) {
console.log("failed");
});
}
});
user service
app.service('user', function () {
var property = {};
return {
getProperty: function () {
return property.nome;
},
setProperty: function (value) {
property.nome = value;
}
};
});
You could just watch your service for changes by adding this code to your MainCtrl:
$scope.$watch(function () { return user.getProperty();}, updateProp, true);
function updateProp(newValue, oldValue) {
$scope.user = {
nome: newValue
};
}
updateProp gets executed everytime the value of user.getProperty() changes.
Your main issue is with your MainCtrl . In the initial execution of MainCtrl there is no value set into your service so its get blank. MainCtrl executes before setting the value in the service.
$scope.user = {
nome: user.getProperty()
};
this code should be executed after setting the value in the service but it executes in the initialization of controller.
You can get the reference from the fiddle below.
http://jsfiddle.net/ADukg/9799/

AngularJS: Data could not be saved

Currently I am trying to save an updated function using angularJS. Till now i can edit the data, the data are can be updated on the database side, but its not showing in the frontend side. Unless i have to logout and login once again to view the updated result. Can i know how to fix this bug.
This is my controller.js code:
.controller('FilmDetailController', //havent done yet
[
'$scope',
'dataService',
'$routeParams',
'$location',
'$window',
'UserInfo',
function ($scope, dataService, $routeParams, $location,$window, UserInfo){
//var userName=dataService.getSessionService('user');
if(UserInfo.loggedIn){
$scope.film = [ ];
$scope.filmCount = 0;
var getFilmDetail = function (moviecode) {
dataService.getFilmDetail(moviecode).then(
function (response) {
$scope.film = response.data.ResultSet.Result;
//$scope.userLoginEmail = dataService.getSessionService('userEmail');
$scope.showSuccessMessage = true;
$scope.successMessage = "Film Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
$scope.editedFilm = {};
$scope.save_note = function ($event,film) {
$scope.editedFilm = film;
dataService.saveNote($scope).then(
function (response) {
// getFilmDetail();
$window.location.href = '#/movieList';
//$window.location.reload();
console.log("done");
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
);
// $scope.reloadRoute = function () {
// $location.path('/movieList');
// $window.location.reload()
// }//end of reload route fnction
}
// only if there has been a courseid passed in do we bother trying to get the students
if ($routeParams && $routeParams.filmid) {
// console.log($routeParams.filmid);
getFilmDetail($routeParams.filmid);
}
}else{
$location.path('/login');
}
}
]
);
Once i click on the save note button the note should be updated in both angular side and also the database side. Currently it can only be updated in the database side except the angular side. Thanks in advance for the help.
From what I can tell it looks like you need to store your note data in a service, and when the note has been successfully saved in your database, you need to push the new note into your service data.
I created a simple fiddle: https://jsfiddle.net/robrothedev/vgbqyv10/
function ItemService() {
var service = {
items: [],
addItem: addItem
};
return service;
function addItem(new_item) {
// run your http request and if the response is valid,
// push the new item to your service array
// $http.post(url,new_item).then(function(response) {
// service.items.push(response.data.new_item);
// });
}
}
function ItemsCtrl(ItemService) {
var vm = this;
vm.items = ItemService.items;
vm.new_item = {};
vm.addItem = addItem;
function addItem() {
ItemService.addItem(vm.new_item);
vm.new_item = {};
}
}

AngularJS Initialize provider data

I have code:
angular.module('admin', [])
.provider('users', function () {
this.users = 'default';
this.$get = function () {
var that = this;
return {
getUsers: function () {
return that.users;
}
}
};
})
.run(function (users, $http) {
users.users = $http('url'); // and others
})
.controller('test', function ($scope, users) {
$scope.users = users.getUsers();
});
I would like to intitalize data in .run() method (I can't use .config() method because it doesn't let to pass any services like $http). I found .run() method, but this code doesn't work... Data aren't saved in provider. Official documentation says:
"Execute this function after injector creation. Useful for application initialization."
I think it's best way to initialize data.
You may want to use an Angular Factory/Service for this kind of need. That is what I do. And pass that into the application. That service will be your singleton or source of truth about the dat.
angular.module('myData.services', [])
.factory('myData', ['$rootScope', '$http' , function($rootScope,$http) {
var factory = {
myData : {}
};
$http('/api/call', function(apiData) {
factory.myData = apiData;
});
return factory;
}]);
You could then use this in your controllers:
angular.module('myApp.controllers', [])
.controller('myCtrl', ['myData', '$scope', function(myData, $scope){
$scope.users = myData;
}]);
Check out the documentation on services: https://docs.angularjs.org/guide/services
Second attempt
angular.module('admin', [])
.factory('users', function ($http) {
var users = {};
var data = [];
$http.get('database.php')
.then(function (response) {
data = response.data;
});
users.getData = function () {
return data;
};
return users;
})
.controller('test', function ($scope, users) {
console.log(users.getData());
});
I would like to have data private. Empty Array returned, reponse comes with all data.
Provider configuration can be doable inside config block only, you can't do that inside run block
Though I don't find a reason to load users object while configuring app. I'd say that you should use either service/factory for this.
Code
angular.module('admin', [])
.service('users', function($http, $q) {
var users = [];
//make an get call to fetch users
function getUsers() {
return $http.get('database.php')
.then(function(response) {
data = response.data;
});
}
//will make a call if users aren't there
this.getData = function() {
// Handled below two conditions
// 1. If users aren't fetched the do an Ajax
// 2. If last ajax doesn't return a data then DO it again..
if (users.length > 0)
return $q.resolve(data); //do return data using dummy promise
return getUsers();
};
return users;
})
.controller('test', function($scope, users) {
users.getData().then(function(data){
console.log(data);
});
});

How to change resource's headers in angularjs

I'm trying to set the headers of a resource (code bellow).
It happens that, when I instantiate my resource ($scope.user = new rsrUser;) angularjs fetches the cookies that aren't yet defined (an "undefined" error is fired from inside "getHMAC()"). The cookies will only be defined when "$scope.login()" is fired (it happens when the user clicks a button in the interface).
Is there a better way of doing this?
controllers.js
angularjsWebInterfaceControllers.controller('loginCtrl', ['$scope', 'rsrUser',
function($scope, rsrUser){
$cookieStore.put("username","therebedragons");
$cookieStore.put("password","therebedragons");
$scope.user = new rsrUser;
$scope.user.username = ""; //bound to input field in interface
$scope.user.password = ""; //bound to input field in interface
$scope.login = function() {
$cookieStore.put("username", $scope.user.username);
$cookieStore.put("password", $scope.user.password);
$cookieStore.put("state", "loggedOUT");
$scope.user.$logIn(
function(){
$cookieStore.put("state", "loggedIN");
}, function() {
$cookieStore.put("username","therebedragons");
$cookieStore.put("password","therebedragons");
$cookieStore.put("state", "loggedOUT");
}
)
};
}]);
services.js
angularjsWebInterfaceServices.service('rsrUser', [ '$resource', '$cookieStore',
function($resource, $cookieStore){
var req = "/login"
var timestamp = getMicrotime(true).toString();
var username = $cookieStore.get("username");
var key = $cookieStore.get("password");
return $resource(baseURL + req, {}, {
logIn: {method:'POST',
isArray:false,
headers:{
'X-MICROTIME': timestamp,
'X-USERNAME': username,
'X-HASH': getHMAC(username,timestamp,req,key)
}
}
});
}]);
EDIT: Actually, the cookies are defiend as soon as the controller is instantiated;
The value for a header can be a function that returns a string (see arguments here: http://docs.angularjs.org/api/ng/service/$http#usage). That way the cookie isn't accessed in your resource until the logIn method is called.
return $resource(baseURL + req, {}, {
logIn: {method:'POST',
isArray:false,
headers: {
'X-MICROTIME': timestamp,
'X-USERNAME': function() {
return $cookieStore.get("username");
},
'X-HASH': function() {
var username = $cookieStore.get("username");
return getHMAC(username,timestamp,req,key)
}
}
}
});

Angular dynamcly setting the user's language

I have a service that fetches the Userinfo which contains his or hers preferred language and I want to use it in my controller to change the language of my application when the user loggs in,
however when I do '$scope.User.locale' which should return the preferred language I keep getting undefined.
My code is:
(function () {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('mainController', function mainController($scope ,UserService, NavigationService, $translate, localStorageService) {
localStorageService.clearAll();
$scope.User = UserService.getUserinfo();
$scope.setLang = function (langKey) {
$translate.uses(langKey);
$.removeCookie(Constants.cookie_locale);
var domain = document.domain;
$.cookie(Constants.cookie_locale, langKey, {path: "/", domain: domain});
};
$scope.logout = function(){
NavigationService.logout();
};
console.log($scope.User);
console.log($scope.User.locale);
$translate.uses($scope.User.locale);
});
}());
UserService:
(function(){
'use strict';
var userServices = angular.module('portal.services');
userServices.factory('UserService', ['UserInfo','localStorageService', function(UserInfo, localStorageService){
return new UserService(UserInfo, localStorageService);
}]);
function UserService(UserInfo, localStorageService){
this.UserInfo = UserInfo;
this.localStorageService = localStorageService;
}
UserService.prototype.getUserinfo = function(){
var userinfo = this.localStorageService.get(Constants.key_userinfo);
if(userinfo !== null){
return userinfo;
} else {
return this.UserInfo.query($.proxy(function(data){
this.localStorageService.add(Constants.key_userinfo, JSON.stringify(data));
}, this));
}
};
UserService.prototype.clearUserInfo = function(){
this.localStorageService.remove(Constants.key_userinfo);
};
}());
Userinfo:
(function(){
'use strict';
var data = angular.module('portal.data');
data.factory('UserInfo', function($resource){
return $resource('/users-rs/api/userinfo',{}, {
query: {method: 'GET'}, isArray: false}
);
});
}());
$scope.User does bind the correct features to the elements I want so I know it's somewhere in there :p, Also when the page is loaded and the setLang function is called it does it's magic, now I only need to get it working on initial loading of the app.
Thx for checking into it
J.

Categories

Resources