I have been working on integrating a register with Facebook feature into an Angular 5 application. Utilizing the Facebook SDK for JavaScript has presented a challenge due to the asynchronous nature of the authentication methods, making it difficult to redirect to the home route URL within them.
Any assistance with this issue would be greatly appreciated.
Here is a snippet of my code:
The register component includes a Facebook component like so:
register.component.html:
<facebook (successfulFacebookLogin)="onsuccessfulFacebookLogin($event)"></facebook>
The Facebook component implementation is as follows:
declare var window: any;
declare var FB: any;
....
export class FacebookComponent implements OnInit {
@Output() successfulFacebookLogin: EventEmitter<boolean> = new
EventEmitter<boolean>(); //event to pass data to the parent container
constructor(private _router: Router, private _loginService: LoginService) {
// Initialize the FB variable using this function
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = '//connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
let thiss=this;
window.fbAsyncInit = () => {
FB.init({
appId: 'xxxxxxxxxxx',
autoLogAppEvents: true,
xfbml: true,
version: 'v2.10'
});
FB.AppEvents.logPageView();
};
}
//Method called when clicking on button Register with Facebook
loginWithFacebook()
{
let globalThis = this;
FB.getLoginStatus((response) => {
if (response.status === 'connected') {
FB.api('/me?fields=id, name, first_name,last_name, picture', function (response) {
console.log(response);
globalThis._loginService.setFacebookUser(response.first_name, response.last_name, response.id, '', '', response.picture.data.url);
});
this._router.navigate(['./home']);
}
else {
FB.login((loginResponse)=>{
this._router.navigate(['./home']);
});
}
});
}
}
Despite efforts to redirect to the home page, a strange occurrence happens where both components are loaded simultaneously on the same page and the URL changes to /home. The home component fails to initialize properly. This issue can be avoided by redirecting before calling the FB.getLoginStatus method, as indicated in the comments.