typescript Angular 2 Facebook 登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37770471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:34:09  来源:igfitidea点击:

Angular 2 Facebook Login

javascriptfacebooktypescriptangular

提问by Paulo Tokarski Glinski

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.

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

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 memethod is used to fetch the users information, like its name, first name etc. When I logged in condition browser console print the following line:

基本上,当页面加载时,我检查用户是否登录到 Facebook,如果没有,我调用 login 方法。在我的方法来获取用户的信息,就像它的名字,名字等。当我在状态浏览器控制台登录打印以下行:

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.

但是用户只存在于方法中。如果我在外面打印它,它什么都不返回。
我只想在网站页面上打印用户名等。我用 Angular JS 做了几乎同样的事情并且运行良好。

Please! Help me!

请!帮我!

采纳答案by reda igbaria

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

回答by EL missaoui habib

For the facebook javascript SDK, You just add the following line in your index.html

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

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

and in ngOnInit() :

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

回答by Ajeet Singh

Angular 2 Service level implementation

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

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

调用者级别函数,此代码将在您的重定向 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']);     
    }

回答by Rob Starling

thishas a bunch of magic involved. Does it help if you capture the class's thisin a variable and use thatin the callbacks (so as to avoid caring what theirthisis)?

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

e.g.

例如

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