Paulo Tokarski Glinski Paulo Tokarski Glinski - 24 days ago 18
TypeScript Question

Angular 2 Facebook Login

(Sorry about my English)

I am developing a website that needs a login with the user's Facebook account. I am using Angular 2 and, of course, TypeScript.

Well, I did it.

But not exactly what I wanted. The login happens ok, but 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 loged on Facebook, if not, I call the login method.

The me method is used to return the users information, like its name, first name etc. When I loged that happens (console.log):

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 it in a User! 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 will return 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!

Answer

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' });
}