I'am trying to import a user's gmail contacts using Angular Js. The code is working fine in plain javascript but giving error in angular js.
HTML Code..
<a class="btn btn-primary btn-simple" ng-click="importgoogle()"><u>Import Gmail Friends</u></a>
Angular Code..
var clientId = 'Client ID';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$scope.importgoogle = function(){
window.setTimeout(authorize); //calls authorize()
}
var authorize = function(){
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization); //calls handleAuthorization()
}
var handleAuthorization = function(){
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
console.log(response);
});
}
}
After entering a user's Id & password the following error message is displayed in console..
Uncaught ReferenceError: authorizationResult is not defined
Can't understand where I'm going wrong as this code is working in Javascript.Please help..
Here is the working example using Angular Js:
app.controller("importGCCtrl", function($scope, $http) {
$scope.config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
$scope.inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
$scope.fetch(gapi.auth.getToken());
});
}
$scope.fetch = function(token) {
$http.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json").then(function(response) {
console.log(response);
//console.log(response.data.feed.entry);
//$scope.contacts = response.data.feed.entry; // to assign data
});
}
});
*NOTE: Please make sure you have included the API - <script src="https://apis.google.com/js/client.js"></script> on the page
The problem lies in the handleAuthorization function. The correct way of implementing that function is..
var handleAuthorization = function(authorizationResult){ //authorizationResult needs to be passed as an arguement.
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
console.log(response);
});
}
}
After making this change the Angular Js code is now working properly.
Related
I am just getting started with AngularJS. I'm coming from backend development, so this JavaScript is confusing for me. I followed the AngularJS tutorial and got the basics working.
I have a "record-list.component.js" file (Name derived from the AngularJS demo) which has a function to download data:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
})
This all works fine. However, I want to add another function that will call a URL so the backend can perform some magic. So I tried something like this:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://blackvue.tozz.nl/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
function DownloadFileController($file) {
$window.alert("Hi: " + $file);
}
})
This does not work. I tried a variety, such as controller: function, but nothing seems to work. Can someone point me into the good direction?
#Luiz Carlos his answer was correct! I got it working with the following code:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
this.DownloadFileController = function ($file) {
window.alert("Hi!");
}
}
})
And in HTML I can do:
<button ng-click="$ctrl.DownloadFileController()">Test</button>
Thanks!
I am learning how to use angular javascript alongside my favorite, PHP framework (CodeIgniter). I have a login section that authenticates to a service and gets the response using angular js. The code works fine. See snippet below
var login = angular.module('authenticationApp' , ['ngMaterial' , 'ngRoute']) ;
login.controller('authenticationController', function ($scope, $http) {
$scope.authenticate = function () {
if ($scope.username == undefined || $scope.password == undefined) {
$scope.login_error_message = "All form fields are required" ;
} else {
var url = get_base_url() + 'student/authentication/login?username=' + $scope.username + '&password=' + $scope.password ;
$http.post(url).then(
function (response) {
console.log(response) ;
/*Here I handle success*/
}, function (response) {
$scope.login_error_message = "Service Error!. Response: " + response ;
}
) ;
}
} ;
My problem is how can I send that response to the success.php page and also redirect to the success page. I can redirect using
window.location.href = get_base_url() + 'administrator/authentication/dashboard' ;
My challenge now is actually sending the response to this new location.
Thanks in advance and I am ready to provide more details if need be
After battling for long, I just decided to use plain js. Crappy but works.
Since firebase did their major update, it has been nearly impossible for me to find answers to basic questions. Even using their docs.
My question is how do I allow my users to sign in once on my app and stay logged in indefinitely or for a set amount of time?
Once I have a user logged in, how can I access their data? Like first and last name? Do I have to create a database and link to the userID somehow?
I am also struggling to understand how "firebase.auth().signInWithEmailAndPassword(email, password)" works since I am not providing it my firebase url. is it pulling it from the config obj on the index page?
Here is my angular code:
appControllers.controller('userCtrl', ['$scope', '$rootScope', '$ionicPlatform', '$cordovaDevice', '$mdToast', '$mdBottomSheet', '$timeout', '$stateParams', '$state', 'LogIn', 'SignUp', '$http', '$firebaseAuth',
function($scope, $rootScope, $ionicPlatform, $cordovaDevice, $mdToast, $mdBottomSheet, $timeout, $stateParams, $state, LogIn, SignUp, $http, $firebaseAuth) {
var devid;
$scope.id = "1";
$scope.errorMsg = "";
// timeout to get device ID
$timeout(function() {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
$scope.id = $cordovaDevice.getUUID();
return $scope.id;
}
}, 1000);
// watches change in DEVID
$scope.updateID = function() {
devid = $scope.id;
console.log(devid);
return devid;
};
$scope.initialForm = function() {
$scope.moveBox = function() {
// $("#signupbox").fadeOut();
$('#signupbox').animate({
'marginTop': "+=170px" //moves down
});
$timeout(function() {
$state.go('app.signup');
}, 500);
$timeout(function() {
$('#signupbox').animate({
'marginTop': "-=170px" //moves down
});
}, 1000);
} // end animate
// Toast for empty Fields
$scope.showAlert = function(menuName, time) {
//Calling $mdToast.show to show toast.
$mdToast.show({
controller: 'toastController',
templateUrl: 'toast.html',
hideDelay: time,
position: 'top',
locals: {
displayOption: {
title: menuName
}
}
});
} // End showToast.
// check LogIn
var em, pw;
$scope.user = {};
$scope.updateEmail = function() {
em = $scope.user.email;
console.log(em);
return em;
};
$scope.updatePass = function() {
pw = $scope.user.pass;
console.log(pw);
return pw;
};
// Password Validation
$scope.validatePass = function(ppw) {
if (ppw.length < 8) {
$scope.errorMsg = "Password must be at least 8 characters long";
}
};
// start login
$scope.logInNow = function() {
var sdata = {
em: em,
pw: pw
};
if (pw == "" || pw == null) {
$scope.errorSignIn = "Fields cannot be blank";
}
// FIREBASE LOGIN
else {
firebase.auth().signInWithEmailAndPassword(sdata.em, sdata.pw)
.then(function(authData) {
console.log("Logged in as:", authData.uid);
$state.go('app.types');
}).catch(function(error) {
console.error("Authentication failed:", error);
$scope.errorSignIn = "Email or Password is invalid";
});
}
}
};
$scope.initialForm();
}
]);
Staying logged-in forever is default behaviour, but it is all about cookies, so if Ionic clears cookies the user get logout. I'm not into Ionic so I guess you need to figure it out whether it is something with Ionic. Related Ionic blog post. If you want to logout user at some point you can do this by setting a timer and just logout user after X time passed. Note that this is a client-side operation.
In my web app I did something like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
$scope.photoURL = user.photoURL;
$scope.name = user.displayName;
$scope.logged_in = true;
} else {
$scope.photoURL = "";
$scope.name = "";
$scope.logged_in = false;
}
});
It works, since every time user enter app the state is changing I always have correct data (Firebase User Interface). I remember there was another way to make it, but I had some issues.
Firebase is first configured and then initialized and every call you do on your app is configured for your project. So yes it is pulling from config.
By the way. Are you using the new docs like https://firebase.google.com/docs/. I am asking because they are actually pretty nice.
I am trying to bind from a http get request. The http get is returning true or false. I have tested the get and it is returning properly. When I run the code below, it shows the alert(1111) properly also. However, when I'm trying to change the button text, nothing appears! I have tried everything that I know to do. Any advice would be helpful.
Post.js
myApp.controller('FollowController', ['$scope', '$http', function($scope, $http) {
var status = "";
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
$scope.statusMessage = data;
} else {
//Following - show Follow
$scope.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}]);
Html
<span style="float: right" ng-controller="FollowController as follow">
<button type=" button" class="btn btn-success" onclick="location.href='#Url.Action("Follow", "Home", new { idToFollow = ViewBag.ProfileId, followerId = User.Identity.GetUserId() })'">
{{ follow.statusMessage }}</button>
</span>
You should bind the variables to this instead of $scope as you are using controllerAs approach
Controller
myApp.controller('FollowController', ['$scope', '$http',
function($scope, $http) {
var status = "";
var follow = this;
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
follow.statusMessage = data;
} else {
//Following - show Follow
follow.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}
]);
I am getting an error origin_mismatch message when I try to use the Google Calendar API through another site that uses a different port.
The code doesn't return an error when the API request is sent from http://original.domain.edu.
However, the code returns the above title error when the API request is sent from https://original.domain.edu:444 (which is the secure login port that the app uses).
I've added both https://original.domain.edu:444 and https://original.domain.edu to my OAuth client in my API console but the same error is still occurring. Can someone offer some help on this?
var exportCalendarToGoogle = function() {
var clientId = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var scope = 'https://www.googleapis.com/auth/calendar';
var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var withGApi = function() {
console.log("gapi loaded");
setTimeout(function() {
gapi.client.setApiKey(apiKey);
gapi.auth.init(checkAuth);
}, 500);
}
var checkAuth = function() {
gapi.auth.authorize({client_id: clientId, scope: scope, immediate: false}, handleAuthResult);
}
var handleAuthResult = function(authResult) {
if(authResult) {
gapi.client.load("calendar", "v3", exportCalendar);
} else {
alert("Authentication failed: please enter correct login information.");
}
}
...
You need a server side file to act as a proxy/bridge to get around JS Origin issues.
eg: var scope = "https://original.domain.edu:444/proxy.php";
<?php
//proxy.php file
echo file_get_contents('https://www.googleapis.com/auth/calendar?' . http_build_query($_GET) );
?>