Angular-fullstack get user id - angularjs

I'm using angular-fullstack to build a single page application, and in one of my controllers I'm trying to assign a user's id to a variable. The code
$scope.getCurrentUser = Auth.getCurrentUser;
returns
function () {
return currentUser;
}
This works fine for displaying in my view as my angular code can interpret the function and display the user id using {{getCurrentUser()._id}} which I'm assuming evaluates the promise and displays the code to the view.
My question is how do I assign $scope.getCurrentUser = Auth.getCurrentUser; to a variable in my controller? Whenever I do so, I get undefined variables. I've tried:
$scope.getId = Auth.getCurrentUser()._id;
console.log($scope.getId); //undefined
$scope.getId = Auth.getCurrentUser();
console.log($scope.getId._id); //undefined
I've read forum posts like this and this that explain that these methods are meant to be returned the way they are. Another post that is basically the same question as mine, but I'm still confused how to store the user id becuase the answer was hinting it was console.log that was the issue. Any help would be greatly appreciated, thanks.

Try the following and let me know how this works out:
angular.module('yourModuleName').controller('YourController', ['$scope', 'Authentication',
function($scope, Authentication) {
var authentication = Authentication;
$scope.getId = authentication.user._id;
console.log($scope.getId);
}
]);
Make sure Authentication is included in your controller.

Related

PassportJS, AngularJS, $rootScope function is not defined

I’m building an app for 1 admin to be able to log in and edit content. When logged in the app will serve up a private html doc structure instead of those not logged in being presented the normal public docs. I’m using Angular-route, Session and Passport for authentication. I want to check if a user is logged in whenever they link to another page on the site. So, if they go somewhere they’re not authorized to be, they can’t edit content on the site.
I’m getting an $injector:modulerr when I run the app on a localhost. The ReferenceError says checkAuth is not defined.
I tried creating a global variable using $rootScope as suggested here:
app.run(['$rootScope', '$http', function($rootScope, $http){
$rootScope.checkAuth = function(){
console.log("rootScope things are happening");
$http.get('/login/loggedin').success(function(user){
if (user !== '0') {
console.log('Authenticated');
return true;
} else {
console.log('Not Authenticated');
return false;
}
});
};
}]);
So, if the user’s logged in, I should get a true and if they’re not logged in, I’ll get a false. But, I still get the checkAuth is not defined injector error and I never see any of my console logs.
The Angular documentation for $rootScope says to use this format:
$rootScope.Scope([providers], [instanceCache]);
So, I tried this:
$rootScope.Scope(['$rootScope', '$http', function($rootScope, $http){...
Unfortunately, that doesn’t work either.
This is an example of using Passport and Angular together which I found somewhat helpful, but they’re allowing multiple users to register (which I don’t want) and it still doesn’t solve the question of a global function for checking if a user is logged in across multiple pages in a website. It may help you to see a similar controller and route file though.
I know that you can use factories and services to do something similar as suggested in previous similar questions, but I was hoping to go this route before trying a different path. Obviously though, if that's the best way, I'll give it a go.
The provided rootscope declaration seems ok to me.
Assign a rootscope value.
app.run(function($rootScope) {
$rootScope.checkAuth = function(){
$http.get('/login/loggedin').success(function(user){
if (user !== '0') {
return true;
} else {
return false;
}
})
};
});
Use it like (don't forget $rootscope dependancy)
app.controller('myCtrl', function($scope, $rootScope) {
$scope.authenticated = function() {
return $rootScope.checkAuth ;
};
});
See live sample to compare: http://jsfiddle.net/TmPk5/6/

Issues with single-requests in Restangular

I'm having a slight issue with my ability to consume REST data retrieved via Restangular in an angular controller. I have the following code which works fine for a list of accounts:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.accounts = accounts;
});
This works perfectly for a list. I use similar syntax for a single account:
var baseAccount = Restangular.one('accounts');
baseAccount.getList(GUID).then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
I am using ng-repeat as the handling directive for my first request. I am attempting to bind with {{ account.name }} tags for the single request, but it does not seem to display any data despite the request being made properly. GUID is the parameter I must pass in to retrieve the relevant record.
I have combed through Restangular docs and it seems to me like I am composing my request properly. Any insight would be greatly appreciated.
EDIT: I've tried all of the solutions listed here to no avail. It would seem Restangular is submitting the correctly structured request, but when it returns it through my controller it shows up as just a request for a list of accounts. When the response is logged, it shows the same response as would be expected for a list of accounts. I do not believe this is a scoping issue as I have encapsulated my request in a way that should work to mitigate that. So, there seems to be a disconnect between Request -> Restangular object/promise that populates the request -> data-binding to the request. Restangular alternates between returning the array of accounts or undefined.
Have you looked at:
https://github.com/mgonto/restangular#using-values-directly-in-templates
Since Angular 1.2, Promise unwrapping in templates has been disabled by default and will be deprecated soon.
Try:
$scope.accounts = baseAccounts.getList().$object;
try:
var baseAccount = Restangular.one('accounts', GUID);
baseAccount.get().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
The problem here is that it's expecting an array to be returned. I'm assuming that you are expecting an account object. Thus we need to use the get function, intead of getList()
The one() function has a second argument that accepts an id e.g. .one('users', 1). You can take a use of it.
CODE
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.getList('account').then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
OR
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.all('account').getList().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
For more info take look at github issue
Hope this could help you, Thanks.

Firebase syncObject is showing redundant error in my Angular controller

I am building an app for a client who has, as one of their data sets a master list of all their members. I have the data coming in from Firebase and everything runs peachy, but it's not that DRY I am now realizing. I would like to use some of the data from the membership set in other views within the site. I copied the code listed below into other controllers that I need to have access to it and although everything works, my IDE (RubyMine) shows the 'syncObject' as redundant.
So, my question is, if there's a way to code it better and dryer to be used in other views? Thank you for your time.
.controller( 'MembershipCtrl', function MembershipCtrl( $scope, $firebase ) {
var ref = new Firebase("https://myid.firebaseio.com/members");
var sync = $firebase(ref);
var syncObject = sync.$asArray();
$scope.members = syncObject;
});

Angularjs Passing array between controllers

I have been through several tutorials and posts about this topic and still can't seem to figure out what is wrong with my code. To me it seems I am having scoping issues with the data within my service. My code is split up into separate files. Here is my code:
github link : https://github.com/StudentJoeyJMStudios/PetPinterest.git
//in dataService.js
var app = angular.module('se165PetPinterestWebApp');
app.service('SharedData', function ()
{
var categoryOfSelectedAnimals = [];
this.setCatOfSelAnimals = function(pulledCategoriesFromParse)
{
categoryOfSelectedAnimals = pulledCategoriesFromParse;
console.log('after assignment in set::' + categoryOfSelectedAnimals);
};
this.getCatOfSelAnimals = function()
{
console.log('in get::::' + categoryOfSelectedAnimals);
return categoryOfSelectedAnimals;
};
});
in my first controller to set the data in signup.js
app.controller('SignupCtrl',['$scope', 'SharedData', function ($scope, SharedData)
{
var Categories = Parse.Object.extend('Categories');
var query = new Parse.Query(Categories);
query.find({
success: function(results)
{
$scope.availableCategoriesOfAnimals = results;
SharedData.setCatOfSelAnimals(results);
},
error: function(error)
{
alert('Error: ' + error.code + ' ' + error.message);
}
});
};
}]);
Then in my other controller trying to get the data from the array within my service:
var app = angular.module('se165PetPinterestWebApp');
app.controller('CatSelCtrl', function ($scope, SharedData)
{
$scope.availableCategoriesOfAnimals = SharedData.getCatOfSelAnimals();
});
When I print the contents from the SharedData.getCatOfSelAnimals I get 0 every time. Please help. Thank you very much in advance.
EDIT: After playing around with a string a bit I am finding the changed string in the set function is not saved into the service and when I call my get function within my service the string is not changed from the set method. Please help, thank you in advance.
EDIT: So it looks like when I navigate to new page by using window.location.href = '../views/categorySelection.html'; in my signup.js it reloads my dataService.js which re-sets my variables back to nothing. Does anyone have any ideas as to how to fix this?
Edit
First: why you lose data
You need to setup routing properly. Right now you are not changing views but rather using window.location.href to load a new bootstrap file (dashboard.html), i.e. everything saved in memory will be lost. So you have been doing it right, sort of, but the moment you change to dashboard.html all data from Parse is lost.
You can solve this by configuring routes and use $location.url() to change URL. Read more about angular.route here: https://docs.angularjs.org/api/ngRoute/service/$route
The angular way
After looking at your code and running your app I think we need to take a step back. Angular is tricky to get used to but there is a lot of good tutorials. I think you might wanna read some of them to get a better grasp of how it works and how to setup and build your app.
Start here: http://www.airpair.com/angularjs
Boilerplate
Found this boilerplate for an Angular app using Parse. It might be something you could use. https://github.com/brandid/parse-angular-demo
Original
Or an even quicker way to empty $scope.availableCategoriesOfAnimals and then merge new data without breaking reference:
$scope.availableCategoriesOfAnimals.length = 0;
Array.prototype.push.apply($scope.availableCategoriesOfAnimals, pulledCategoriesFromParse);
You are breaking the reference on assignment. This is a JavaScript issue, not an angular one for that matter ;)
Try this in your set function:
categoryOfSelectedAnimals.length=0;
pulledCategoriesFromParse.forEach(function (e) {categoryOfSelectedAnimals.push(e)});
in stead of reassigning
edit: angular extend works on objects, not arrays, so replaced it with a bit of JS.

retrieve data from firebase (angularjs)

UPDATE : find my answer here
A little clarity on getting key values using AngularFire v2?
I looked for many sources before asking a simple question but Im just sarting with firebase and I can't manage to use the data the way I want. What I need, is to retrieve two int in my controller (how much "yes" and how much "no" linked to a question.
the data model is the following
question/id/(text, yes, no)
I have a service where I call my data using an id
app.service('QuestionService', function($firebase,$q) {
var _this = this;
//initialize Firebase
var ref = new Firebase('https://basename.firebaseio.com/question');
this.get = function(nb){
var QuestionObject = ref.child(nb);
return $firebase(QuestionObject);
};
return this;
});
I have a controller function where I call some data using a random id
$scope.pickQuestion = function(){
var randomnumber = Math.ceil(Math.random() * 3);
$scope.message = QuestionService.get(randomnumber);
};
and then it works great so I can have something like
{{message.yes}} or {{message.no}} and get the corresponding integer.
My issue, what I want to do, is to pass this "message.no" value to my controller. I don't know what to do. I can't manage to get the value directly inside the controller (it works only inside the view) and I can't manage to pass the value to my controller from the view. I tried a
ng-init="functionName({{message.yes}}, {{message.no}})"
but it return an error into the console. (however the source a displayed correctly)
Does someone could guide me into the right direction?
Thanks

Resources