Angular 2 Facebook登录

时间:2016-06-12 03:31:29

标签: javascript facebook typescript angular

我正在开发一个需要使用Facebook帐户登录的网站。我正在使用Angular 2,当然还有TypeScript。它有效但不完全是我想要的。我无法收回用户的信息。

让我们转到代码:

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

基本上,当页面加载时我检查用户是否登录到Facebook,如果没有,我调用登录方法。 me 方法用于获取用户信息,如名称,名字等。当我登录条件浏览器控制台时,打印以下行:

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

一切都好!但是我希望得到那个Object并放入User对象!这样的事情:

me method

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

但是用户只是存在于方法内部。如果我在外面打印,它什么也不返回 我只想在网站页面打印用户名等。我使用Angular JS几乎做了同样的事情并且效果很好。

请!救救我!

4 个答案:

答案 0 :(得分:7)

您可以使用胖箭头功能来使用相同的上下文...

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

答案 1 :(得分:3)

对于facebook javascript SDK,您只需在index.html中添加以下行

<script src="//connect.facebook.net/en_US/sdk.js"></script>

并在ngOnInit()中:

    `FB.init({
        appId      : 'your-app-id',
        cookie     : false, 
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });`

答案 2 :(得分:3)

Angular 2服务水平实施

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

来电级别功能,此代码将位于重定向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']);     
    }

答案 3 :(得分:0)

this涉及到一堆魔法。如果您在变量中捕获类this并在回调中使用 (以避免关注他们的 this是什么,这会有帮助吗? )?

e.g。

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