Read Meteor Session on a different page - javascript

I want to display a "Welcome back" message on the home page after the user performs a successful signIn. However, after I make a redirect with Router.go('home');, I can't read the Session within my Template.home.rendered = function().
Here is my code:
Login logic:
Meteor.loginWithPassword(username, password, function(err) {
if (err) {
showError();
} else {
Session.set('signInSuccess', true);
Router.go('home');
}
});
Template.home.rendered = function() {
console.log(Session.get('signInSuccess'));
if (Session.get('signInSuccess') == true) {
showWelcomeMessage();
Session.set('signInSuccess', null);
}
}
Any help would be greatly appreciated.

This is simply because Template.home.rendered is executed exactly once when your template is first inserted in the DOM (it may get executed again if the template is destroyed and reinserted, via the routing mechanism).
See rendered behavior here : http://docs.meteor.com/#template_rendered
Try wrapping your verification code inside an autorun :
Template.home.rendered=function(){
// setup a reactive computation to watch for Session variable modification
this.autorun(functon(){
// using Session.equals is better than checking against Session.get
// see http://docs.meteor.com/#session_equals
if(Session.equals("signInSuccess",true)){
showWelcomeMessage();
Session.set("signInSuccess",false);
}
});
};

Related

angularjs: open a page then only loading data

My current ionic code able to get data then open the page. However, I want to open the page then only loading to get the data. I want to change the sequence since it takes 10s to load some data.
Here is my code:
$scope.openDetail = function (stock) {
console.log(stock.symbol);
$ionicLoading.show();
//stockCondition
if(stock.symbol.length<=$scope.stockCondition) {
$stockDataFactory.getStockDetails(stock).then(
function success(data) {
$globalFactory.personalStockData = data.details;
$globalFactory.personalStockNews = data.news;
$ionicLoading.hide();
$state.go("app.page1");
},
function error(error) {
alert(error.message);
console.error(error);
$ionicLoading.hide();
}
);
}
else{//WarrentCondition
$stockDataFactory.getWarrentDetails(stock).then(
function success(data) {
$globalFactory.personalStockData = data.details;
$globalFactory.personalStockNews = {};
$ionicLoading.hide();
$state.go("app.page1");
},
function error(error) {
alert("Stocks Not Found.");
console.error(error);
$ionicLoading.hide();
}
);
}
};//end
In order to open the $state.go("app.page1"); first, then only loading data, how shall I made changes of my code?
You should show the page1's html templet .
My approach will be using ng-if="personalStockData" with the $setTimeout() trick to show the data only when it's loaded. looks something like this
//page1 controller
$stockDataFactory.getStockDetails(stock).then(
function success(data) {
$setTimeout(function(){
$scope.personalStockData = data.details;
$scope.personalStockNews = data.news;
})
},
function error(error) {
alert(error.message);
console.error(error);
$ionicLoading.hide();
}
);
html
<div>
...
<div ng-if="personalStockData">
</div>
<div ng-if="personalStockNews">
</div>
...
</div>
anyways try not to use global variables, those are really hard to track.
You'll have to bring over the decision data that are explicit to the current page over to app.page1. For instance $scope.stockCondition. I suspect it is the same forstock.symbol. Will have to see what stock variable is.
There are many ways you can achieve this. Using query string is one option and is also the most conventional way. Some people prefer to store them in cookies, not efficient but applies to certain use-cases.
Again, I am not sure what $state is. Assuming it is angular-ui-router's statemanager. Then you can achieve this by;
$state.go("app.page1", {
stockCondition: $scope.stockCondition,
stocksymLen: stock.symbol.length
});
Then on app.page controller you can retrieve the values of the query string parameters by doing $state.params.stockCondition.
Once you have brought the decision variables across to the next page. The next step would be to plug them into the if-else statement you got from the other page onto app.page1.
Pseudo code:
angular.module('blah')
.controller('app.page1', function($scope, $state) {
// on page load
if($state.params.stocksymLen <= $state.params.stockCondition) {
// do your REST call
...
else {
...
}
});

GoogleAuth.signOut() does not work

I have a google sign-in button on my page, using gapi.signin2.render to render the button (https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid-options).
However it ALWAYS renders as signed-in, despite calling GoogleAuth.signOut(). In fact I can actually call GoogleAuth.signOut() and immediatly check GoogleAuth.isSignedIn.get() to check the state and returns as true.
Does anyone know how to fix this? My sign-out code is as follows:
var GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.signOut().then(() => {
var status = GoogleAuth.isSignedIn.get(); //ALWAYS TRUE!!!!
alert('IP.common.oAuth.signOut: signin status: ' + status);
});
This should be work fine. Delete then(this.props.onLogoutSuccess)) if you don't need it.
signOut() {
if (window.gapi) {
const auth2 = window.gapi.auth2.getAuthInstance()
if (auth2 != null) {
auth2.signOut().then(auth2.disconnect().then(this.props.onLogoutSuccess))
}
}
}
Very nice lib, if you wanna learn how to work with Google API https://github.com/anthonyjgrove/react-google-login. Yes it's react, but methods should be similar, I think.

FB SDK Version 2.4 not returning value for /me/groups

I am trying to get the User's groups list with the following code:
$(document).ready(function() {
$("#fetchButton").click(function() {
console.log('fetch button');
FB.getLoginStatus(function(res){
if( res.status == "connected" ){ // check if logged in
// get user data first, which will be handled by an anonymours fucntion passed inline
FB.api('/me', function(meResponse) {
//console.log(meResponse);
UID = meResponse.id;
getGroups();
console.log(meResponse);
});
} else { // if not logged in, call login procedure
FB.login(function(){
$("#fetchButton").click();
}, {scope: 'publish_actions, publish_actions, read_stream, user_groups'});
}
});
});
});
function getGroups() {
FB.api('/me/groups', function(groupResponse) {
console.log(groupResponse);
});
}
This code used to work with some old version of FB SDK. But not now.
Any help!
read_stream and user_groups are deprecated and you are using publish_actions two times. In order to get a list of all the groups you manage, you need to use user_managed_groups now.
More information: https://developers.facebook.com/docs/apps/changelog#v2_4

re-execute javascript after log-in

I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}

Refresh Vs. Reload (Cannot call method 'authorize' of undefined) GAPI

I have a simple gapi (Google Drive) app that I want to connect to. There something strange that happening. I have the sample from the demo. https://developers.google.com/drive/web/quickstart/quickstart-js
//Nothing happens
<script src="static/javascript/libs/client.js?onload=Drive._handleClientLoad"></script>
//Works on reload but not refresh
// (reload) "successfully authorization"
// (refresh) "Uncaught TypeError: Cannot call method 'authorize' of undefined"
<script src="static/javascript/libs/client.js" onload="Drive._handleClientLoad"></script>
Javascript:
var Drive = {
_CLIENT_ID: '61183508825.apps.googleusercontent.com',
_SCOPES: 'https://www.googleapis.com/auth/drive.file',
_rootid: null,
authorised: false,
_auth: function() {
gapi.auth.authorize({
'client_id': Drive._CLIENT_ID, 'scope': Drive._SCOPES, 'immediate': true
},Drive._handleAuthResult);
},
_handleClientLoad: function() {
window.setTimeout(Drive._auth, 1);
},
_handleAuthResult: function(authResult) {
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
Drive._validAuth();
} else {
// No access token could be retrieved, show the button to start the authorization flow.
Drive._invalidAuth();
}
},
_invalidAuth: function(){
Drive.authorised = false;
console.log("invalid authorization");
},
_validAuth: function(){
Drive.authorised = true;
console.log("successfully authorization");
},
}
Why is this happening?
The html should be as per your first snippet. You need to figure out why "nothing happens". It might be some limitation in the Google lib that prevents it from calling into a module. Try replacing Drive._handleClientLoad with a global function that in turn calls your module. Perhaps sprinkle a few console.log's or debugger's in to see what is being executed and what isn't.
Not sure why but I can't call Drive._handleClientLoad from the ..client.js?onload= function, so creating a public one like bellow and it works.
function handleClientLoad() {
window.setTimeout(Drive._checkAuth, 1);
}
// ..client.js?onload=handleClientLoad

Categories