As I work on developing a website that requires users to log in with their Facebook account, I am facing some challenges. I am utilizing Angular 2 and TypeScript for this project, but the user information retrieval is not working as expected.
Let's delve into 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);
});
}
}
Essentially, when the page loads, it checks if the user is logged in via Facebook. If not, the login method is invoked. The me method fetches user information such as name and first name. Upon successful login, the browser console displays details like:
Object {id: "666", name: "Paulo Henrique Tokarski Glinski", first_name: "Paulo", gender: "male", picture: Object…}
All seems well! However, I aim to take that object and assign it to a User object. Here's what I have in mind:
me method:
this.user = result;
console.log(this.user);
Unfortunately, the user data only remains within the method scope. When attempting to access it outside, no values are returned. In my previous experience with AngularJS, a similar approach yielded successful results.
If anyone could provide guidance or assistance, it would be greatly appreciated!