Austin737 Austin737 - 5 months ago 24
AngularJS Question

Facebook username not displaying in Angularjs app (using Firebase)

I am attempting to learn both Angular and Firebase but I am running into a problem when I try to display username, profile pic, etc that is returned from Facebook. I can log the object returned from FB to the console and see that it is indeed returning all of the appropriate info, but if I try to display any of the info in my view it does not work so not sure what step I am missing. I have included all necessary scripts so i don't think that is the problem Any advice is greatly appreciated. Also just let me know if I have left out any info that might help to find a solution.

My controller:

'use strict';

angular.module('myApp.login', ['ngRoute', 'firebase'])

.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login/login.html',
controller: 'LoginCtrl'
});
}])

.controller('LoginCtrl', function ($scope, $firebaseAuth, $firebaseObject) {
var ref = new Firebase("https://shining-heat-2026.firebaseio.com");
$scope.login = function () {
ref.authWithOAuthPopup("facebook", function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
var myname = authData.facebook.displayName;
var userName;
console.log("hi" + " " + myname);
console.log(authData);
}
});
$scope.userName = authData.facebook.displayName;
}
});


and view:

<div class="row myrow" ng-controller="LoginCtrl">
<div class="col-lg-4">
<button id="fblogin" type="button" ng-click="login()">FB Login</button>
</div>
<div class="col-lg-4">{{"Hi" + " " + userName}}</div>
<div class="col-lg-4">Right Login</div>
</div>


I have included all of the necessary scripts and bootstrapped the app in my index.html file so I don't that is an issue. Also if I set $scope.username to a string it will display in my view once I fire the login function.

Answer

I agree, way of programming which implies placing lines of code in random places until it starts working provides a lot of fun... However, to stop this game you need to know the correct combination.

ref.authWithOAuthPopup is an asynchronous operation and when it is complete it calls the provided handler. Thus authData exists only in the scope of this function

    ref.authWithOAuthPopup("facebook", function (error, authData) {
        if (error) {
            console.log("Login Failed!", error);
        } else {
            var myname = authData.facebook.displayName;
            var userName;
            console.log("hi" + " " + myname);
            console.log(authData);
            $scope.userName = authData.facebook.displayName;
        }
    });
Comments