Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Facebook Login

I am developing an website that needs to be logged in with Facebook account. I am using Angular 2 and, of course, TypeScript. It works But not exactly what I wanted. I can't take back the user's information.

Let's go to the code:

import {Component} from 'angular2/core';
import {Main} from './pages/main/main';

declare const FB: any;

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html',
  directives: [Main]
})

export class AppComponent implements OnInit { 

token: any;
loged: boolean = false;
user = { name: 'Hello' };

constructor() { }

statusChangeCallback(response: any) {
    if (response.status === 'connected') {
        console.log('connected');
    } else {
        this.login();
    }
}

login() {
    FB.login(function(result) {
        this.loged = true;
        this.token = result;
    }, { scope: 'user_friends' });
}

me() {
    FB.api('/me?fields=id,name,first_name,gender,picture.width(150).height(150),age_range,friends',
        function(result) {
            if (result && !result.error) {
                this.user = result;
                console.log(this.user);
            } else {
                console.log(result.error);
            }
        });
}

ngOnInit() {
    FB.getLoginStatus(response => {
        this.statusChangeCallback(response);
    });
}
}

Basically, When the page loads I check if the user is logged in to Facebook, if not, I call the login method. The me method is used to fetch the users information, like its name, first name etc. When I logged in condition browser console print the following line:

Object {id: "666", name: "Paulo Henrique Tokarski Glinski", first_name: "Paulo", gender: "male", picture: Object…}

Everything ok! But I want to get that Object and put into a User object! Something like that:

me method:

this.user = result;    
console.log(this.user);

But the user just exists inside the method. If I print it outside, its returns nothing.
I just want to print the users name etc. at the website page. I did almost the same thing with Angular JS and worked well.

Please! Help me!

like image 917
Paulo H. Tokarski Glinski Avatar asked Jun 12 '16 03:06

Paulo H. Tokarski Glinski


2 Answers

Angular 2 Service level implementation

import {Injectable} from '@angular/core';
import { Location } from '@angular/common';
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { ConfigService } from "app/core/services/config.service";

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch';

@Injectable()
export class AuthService {

   constructor(private http: Http,
               private configProvider:ConfigService) {
    }
    authenticateFacebook(){
         window.location.href = 'https://www.facebook.com/v2.9/dialog/oauth?client_id='+
         this.configProvider.config.facebook.clientId + 
         '&redirect_uri='+ this.configProvider.config.facebook.redirectURI + '&scope=public_profile';
    }
    getAccessToken(authenticationCode: string){
        var authProviderUrl = 'https://graph.facebook.com/v2.9/oauth/access_token';
        var authParameters = {
            client_id: this.configProvider.config.facebook.clientId,
            redirect_uri: this.configProvider.config.facebook.redirectURI,
            client_secret: this.configProvider.config.facebook.clientSecret,
            code: authenticationCode
        };
        var params = [];
        for (var k in authParameters) {
            params.push(k + '=' + authParameters[k]);
        }
        var authOpenURI = authProviderUrl + '?' + params.join('&');

         return this.http.get(authOpenURI)
                   .map(res => res.json())
                   .catch(err => Observable.throw(err));
    }
    getUserFacebookProfile(accessToken:string):Observable<any>{
        var fields = ['id', 'email', 'first_name', 'last_name', 'link', 'name','picture.type(small)'];
        var graphApiUrl = 'https://graph.facebook.com/v2.5/me?fields=' + fields.join(',');

        return this.http.get(graphApiUrl+'&access_token='+accessToken+'')
                   .map(res => res.json())
                   .catch(err => Observable.throw(err)); 
    }

Caller level function, this code will be in the component of your redirect URI

//Facebook authentication check
    if (window.location.href.indexOf("code") > -1){
      var code = window.location.href.substring(window.location.href.indexOf("?") + 1).split('&')[0].split('=')[1];
      this.getFaceBookProfile(code);
    }
    //Get profile from facebook
    getFaceBookProfile(code:string){
      this.authService.getAccessToken(code).subscribe(oathAccessData => {
        this.authService.getUserFacebookProfile(oathAccessData.access_token).subscribe(profile => {
           this.userProfile = new UserProfile(profile.name,profile.email, profile.picture.data.url,"facebook",
           profile.id);},err => { console.log(err); });},err => { console.log(err);});

                  this.router.navigate(['/dashboard']);     
    }
like image 63
Ajeet Singh Avatar answered Oct 02 '22 18:10

Ajeet Singh


you can use fat arrow functions to use the same context ...

login() {
  FB.login((result: any) => {
    this.loged = true;
    this.token = result;
  }, { scope: 'user_friends' });
}
like image 34
reda igbaria Avatar answered Oct 02 '22 18:10

reda igbaria