This is a preview at a secret URL that can be shared with trusted people. It will update with changes automatically. View the published version .

July 30, 2017

Angular 4 is great but integrating Typescript with pure Javascript SDKs can be a complete nightmare to say the least.

In this post I will show an example of my Facebook login integration with Angular 4 and hopefully by following this method you should be able to work with all parts of the Facebook Javascript SDK.

We are working with a basic Angular 4 component.

First, use the helper on this page to create a button to your specifications and paste it in the html of your component.

Next step is to create a reference outside of the component to the FB variable which we will be assigning asynchronously later and to the javascript window variable.

//imports above declare var window: any; declare var FB: any; @Component({ selector: 'app-account-view', templateUrl: './account-view.component.html', styleUrls: ['./account-view.component.css'] }) export class AccountViewComponent implements OnInit { //Rest of code

Then, In our constructor, we need to paste in the boilerplate code that can be found here here

constructor(private accountManager: AccountManagerService, private router: Router, private http: Http) { // This function initializes the FB variable (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')); window.fbAsyncInit = () => { console.log("fbasyncinit") FB.init({ appId : 'facebook app id here', autoLogAppEvents : true, xfbml : true, version : 'v2.10' }); FB.AppEvents.logPageView(); // This is where we do most of our code dealing with the FB variable like adding an observer to check when the user signs in // ** ADD CODE TO NEXT STEP HERE ** }; }

Next, we need to be notified when the login is a success. To do this, we are going to subscribe to an event that will tell us when the status of the user has changed. We can then do things like save the users Facebook ID to the database or run some other Facebook tasks.

FB.Event.subscribe('auth.statusChange', (response => { if (response.status === 'connected') { // use the response variable to get any information about the user and to see the tokens about the users session } }));

This all works well but there is a problem. When we navigate away from this page, the button goes away. To fix this, we need to tell the FB SDK to parse our html file again. Add this code into the OnInit event.

ngOnInit() { if (window.FB) { window.FB.XFBML.parse(); } }

That should do it. If you have any questions feel free to message me on Twitter.

372 Kudos