Ionic 2 – Facebook Graph Api (updated)

Hi Friends,

This post is again an update to my previous post on Ionic 2 and Fb Graph Api which can be found here.

Now this is quite easy to do, if you had gone through my previous post. There has been a few changes here and there.

A complete screencast of this post.

 

Complete code for this post is available here.

Let’s begin.

Create an ionic 2 app using the below command.

Then open up https://developers.facebook.com/apps

We need to create an app here and assign our app id to it so that we could make use of fb resources in our app.

Detailed and extensive documentation on how to do this is available here.

Assuming that you have created the app in the facebook developer portal let’s move on.

Install the cordova-plugin-facebook4 using the below command.

Please replace APP_ID with the id you get when you register with facebook and the APP_NAME with values you get from the facebook developer portal.

Now open up the project you created in your favorite editor and add the below code in home.html between the ion-content tags.

This will just add three buttons on the screen. Let’s wire these buttons up to three functions.

Open up home.ts and add the below code to it.

If you notice, we are directly importing Facebook from ionic-native and using it directly in our code. Also the login, getLoginStatus functions return a promise. So we are resolving it. The getLoginStatus() not only checks whether the user is logged in or not but also accesses the FBGraph Api using Facebook.api and returns the id,name & gender field.

Don’t forget to add Facebook to providers array in app.module.ts as shown below.

Now run the app on your device. If everything goes fine you should see an app with three buttons. Try logging in and then getting login status. Logout and try getting login status again.

Hope this helped you guys. Thanks for reading. Peace.. :)