I watched a video on lynda, but unfortunately it's not on the latest version of the API.
The video shows how to use firebaseSimpleLogin, but this was changed to authWithPassword if I want a email & password type of authentication.
I can login, logout and register but the
PROBLEM is: I can't verify if the user is logged in or logged out.
here is my code below:
The Factory
GlobalCtrl.factory('Auth', ['$firebaseAuth', function($firebaseAuth){
var ref = new Firebase("https://taxiq-app.firebaseio.com"); //call on firebase database
//var objects = $firebase(ref) // reference database
return $firebaseAuth(ref);
}]);
The controller
taxiGlobalCtrl.controller('LoginController',['$scope','$firebase','Auth' ,'$location', function($scope, $firebase,Auth, $location){
$scope.login = function(){
Auth.$onAuth(function(authData) {
$scope.authData = authData;
console.log($scope.authData);
});
Auth.$authWithPassword({
email: $scope.username,
password: $scope.password
}).then(function(authData) {
console.log("Logged in as:", authData.uid);
$location.path('/tickets');
}).catch(function(error) {
console.error("Authentication failed:", error);
$scope.loginError = "loging error";
});
}
}]);
The naV that will show logout after logged in
<div>
<a class="navbar-brand" ng-href="#">Tiketa</a>
<ul class="nav navbar-nav">
<li ng-hide="authData"><a ng-href="#/login">Login</a></li>
<li ng-hide="authData"><a ng-href="#/register">Register</a></li>
<li ng-show="authData"><a ng-href="#/tickets">Tickets</a></li>
<li ng-show="authData"><a ng-href="#" ng-click="auth.$unauth()">logout</a></li>
</ul>
note: I'm fresh from online resources about angular and firebase,... I'm a noob
Related
Hi guys I had used this code my AngularJS app to execute a GET request, now I want to use it in Angular I have some problems with update it can anyone help me ?
script :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://---:8080/api/v1/users")
.then(function(response) {
$scope.users = response.data;
$scope.AfficherMap = AfficherMap;
console.log(response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
html:
<div ng-controller="myCtrl" style="width: 250px;">
<div ng-repeat="user in users" ng-click="AfficherMap(user.id)">
<a>{{user.id}} {{user.firstName}} {{user.lastName}}</a>
</div>
</div>
You can do this in this way...
Make a get function in UserService:
constructor(http:HttpClient){}
getUsers(){
return this.http.get("api_url");
}
Now In your component call this function.
constructor(private userService: UserService){
}
ngOninit(){
this.userService.getUsers().subscribe((res)=>{
console.log(res); // This is your users list...
this.users = res;
});
}
Now In your html
<div style="width: 250px;">
<div *ngFor="let user of users">
<a (click)="AfficherMap(user.id)">{{user.id}} {{user.firstName}-
{{user.lastName}}
</a>
</div>
</div>
AngularJS(1.x) and Angular(2+) are totally different frameworks, in Angular(2+) you will need to use HttpClient module to do an HTTP call more details on the official doc
Find a suggestion for your code:
getUsers() {
this.api.getUsersCall()
.subscribe(users => {
for (const u of (users as any)) {
this.users.push({
name: u.name,
username: u.username
});
}
});
}
given that api is an instance of the APIService you need to create a module for it and declare it in your component class with the specifier private, APIService module will contains the definition of getUsersCall:
getUsersCall() {
return this.http.get("http://---:8080/api/v1/users");
}
im currently working in ionic framework with inappbrowser but any time i open the external url link it open another broswer but i want it indicate loading spinner so users will know it is loading, i dont know want it to open with system browser
<div class="list">
<a class="item item-avatar" href="#" ng-click="loadData()" onclick="window.open('http://www.mysite', '_blank', 'location=yes'); return false; ">
<img src="img/be1.png">
<h2>site here</h2>
</a>
</div>
and my controller
.controller('MyCtrl', function($scope, $ionicLoading, $timeout) {
$scope.myTitle = 'Loading Sample';
$scope.loadingIndicator;
$scope.counter = 0;
$scope.loadData = function() {
$scope.loadingIndicator = $ionicLoading.show({
template: '<ion-spinner icon="spiral"></ion-spinner>'
});
$timeout(function() {
$ionicLoading.hide();
}, 1500);
};
})
thanks
In loadData() itself add
var ref=window.open('http://www.mysite', '_blank', 'location=no');
(location=no to hide url bar)
ref.addEventListener('loadstart', function() { $ionicLoading.show() });
ref.addEventListener('loadstop', function() { $ionicLoading.hide() });
I am not able to populate data filled inside the array.
My main controller front is this:
<body ng-controller="MainCtrl"> // MainCtrl controller
<ion-nav-view animation="slide-left-right"></ion-nav-view>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
</body>
the MainCtrl initially contain nothing like this:
.controller('MainCtrl', function($scope, $ionicSideMenuDelegate, $ionicPopover, $state, $timeout) {
$scope.users = [];
$scope.devices = [];
})
Initially when i do login the controller named intro is getting called that controller calls rest & validate user & on successfully validating it does following:
.success(function(data, status, headers, config) {
if (data.alert === 'SUCCESS'){
var UserData = data.userdata;
var Username = UserData.personal_information.first_name+" "+UserData.personal_information.last_name;
var Email = UserData.username;
var LastLogin = new Date(UserData.last_visited * 1000);
$scope.users = [{ username: Username, email: Email, location: true, id: null, avatar: 'img/men.jpg', enabled: 'true', lastLogin: LastLogin}];
if(data.ownteam == true) {
$.each(data.ownteamdata, function( index, value ){
var TeamId = value.team_id;
var TeamName = value.team_name;
var Status = value.role;
var surveyArray = {id : TeamId, name :TeamName, icon: 'ion-document-text', status : Status, color : Color};
$scope.devices.push(surveyArray);
});
}
now when i console the array it shows me the data inserted.
then i move to dashboard page where the data of devices array need to be polupated & shown like:
<div ng-repeat="device in devices | filter: { featured: true}">
<div class="padding-horizontal">
<div class="item item-icon-left" on-tap="deviceTap('router.device', device)">
<i class="icon" ng-class="device.icon"></i>
{{ device.name }}
<span class="badge" ng-class="device.color">
{{ device.status }}
</span>
</div>
</div>
</div>
but it is not showing the data to me in the page??? is there something i m missing?
You're trying to filter the devices where featured = true
<div ng-repeat="device in devices | filter: { featured: true}">
but you don't seem to have that element in your object:
var surveyArray = {
id : TeamId,
name :TeamName,
icon: 'ion-document-text',
status : Status,
color : Color
};
Another problems could be the fact that you're maybe - trying to access the array from 2 different controllers.
I would suggest to check your console in chrome (F12) and use some sort of debug.
UPDATE:
One approach if you want to share data between controllers is to use a shared service, like a session, so you can move of the login for the login and validation there (clean controllers).
You can have a look at this plunker.
In app.services.js you will find a service called userAccountService.
(function () {
'use strict';
var services = angular
.module('app.services', [])
.factory('userAccountService', userAccountService);
userAccountService.$inject = ['$q'];
function userAccountService($q) {
var service = {
users: [],
devices: [],
logIn: logIn,
};
return (service);
function logIn(username, password)
{
var deferred = $q.defer();
this.users.push({username: username});
this.devices = [{name: 'android'}, {name: 'iphone'}];
deferred.resolve({users: this.users, devices: this.devices });
return deferred.promise;
}
};
})();
It will be responsible for the log-in an for sharing data between controllers ... and other modules. It is a singleton.
This service contains 2 arrays: users and devices:
var service = {
users: [],
devices: [],
logIn: logIn
};
The login method will, presumably, authenticate the user through an http call and will populate the shared members: users and devices.
(I've used promises there to match your $http call).
Now you can have a look at the app.controller.js file where my controllers are defined.
They depend on userAccountService.
view1Controller is the starting point and it is in charge for the login:
$scope.login = function()
{
userAccountService.logIn('username', 'password')
.then(function(result){
$scope.users = result.users,
$scope.devices = result.devices
})
.catch(function(reason){
console.log(reason);
});
$state.go('view2');
}
if the login is successful it will populate the two local members to be displayed in the page.
<div ng-repeat="device in devices">
<div class="padding-horizontal">
<div class="item item-icon-left">
{{ device.name }}
</span>
</div>
</div>
</div>
Same thing happens with view2. Now we don't need to login again; we can simply read the shared member of our service:
.controller('view2Controller', function($scope, userAccountService) {
$scope.users = [];
$scope.devices = [];
function init()
{
$scope.users = userAccountService.users;
$scope.devices = userAccountService.devices;
}
init();
})
Hi I'm just learning angular, and I was wondering if someone could let me know what I'm doing wrong with setting up this simple load bar in the Yeoman signup page
In the signup.controller.js, I have the following code:
'use strict';
angular.module('lolBetApp')
.controller('SignupCtrl', function ($scope, $http, Auth, $location) {
$scope.user = {};
$scope.errors = {};
$scope.register = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.createUser({
summonerName: $scope.user.summonerName,
email: $scope.user.email,
password: $scope.user.password
})
.then( function() {
// Account created, redirect to home
$location.path('/');
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
$scope.$emit('LOAD')
$http.jsonp('http://filltext.com/?rows=10&delay=5&fname={firstName}&callback=JSON_CALLBACK')
.success(function(data){
$scope.people=data;
$scope.$emit('UNLOAD')
});
}).
controller('loaderController',['$scope',function($scope){
$scope.$on('LOAD',function(){$scope.loading=true});
$scope.$on('UNLOAD',function(){$scope.loading=false });
}]);
And in my signup.html, I have the following code:
<div ng-controller="loaderController">
<div class="alert alert-info" ng-show="loading">Summoning...</div>
<div ng-controller="myController">
<ul>
<li ng-repeat="person in people">
{{person.fname}}
</li>
</ul>
</div>
I was able to get this to work easily without using Yeoman, using the code in this link http://plnkr.co/edit/30qbDj0xuBESp6LT8etM?p=info
Does anyone know what I'm doing wrong?
Thanks,
Nevermind! I just got it to work. The problem is that I had the wrong name for the controller in the signup.html page
<div ng-controller="SignupCtrl">
<ul>
<li ng-repeat="person in people">
{{person.fname}}
</li>
</ul>
</div>
I'm following thinkster's ang-news tutorial to build authentication using firebase. I can create users with a service and controller but after registering a new user they are not logged in.
I have a auth.js service:
app.factory('Auth', ['$rootScope', 'FIREBASE_URL', '$firebaseSimpleLogin', function($rootScope, FIREBASE_URL, $firebaseSimpleLogin){
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
register: function(user){
return auth.$createUser(user.email, user.password);
},
signedIn: function(){
return auth.user !== null; // user signed in if user property is not null
},
login: function(user){
return auth.$login('password', user); // type of login
},
logout: function(){
auth.$logout();
}
};
$rootScope.signedIn = function(){
return Auth.signedIn();
};
return Auth;
}]);
auth.user always stays null.
This is my controller:
app.controller('AuthCtrl', ['$scope', '$location', 'Auth', function($scope, $location, Auth){
if (Auth.signedIn()){
$location.path('/')
}
$scope.register = function(){
Auth.register($scope.user).then(function(authUser){
console.log('authUser: ' + JSON.stringify(authUser))
$location.path('/');
})
}
}])
Then I have a register.html with an email/password form. It calls register():
<form ng-submit='register()' novalidate>
<input type='email' placeholder='Email' class='form-control' ng-model='user.email'>
<input type='password' placeholder='Password' class='form-control' ng-model='user.password'>
<input type='submit' class='btn btn-success' value='Register'>
</form>
The users get generated in my Firebase Forge, but after I submit the register form, the Logout button does not show:
<ul class='nav navbar-nav navbar-right' ng-show='signedIn()'>
<li>
<a href='#' ng-click='logout()'>Logout</a>
</li>
</ul>
Why does signedIn() stay falsey after I create a user in the firebase forge?
Creating a user does not automatically log them in (though it used to in an older version of angularFire).
Change your controller method to look like:
$scope.register = function(){
Auth.register($scope.user).then(function(authUser){
console.log('authUser: ' + JSON.stringify(authUser))
Auth.login($scope.user);
$location.path('/');
})
}
This will create the user in the Forge and then once that promise resolves, it will automatically log them in.