FB.api()内部的Angant Cant调用函数

时间:2018-11-26 16:25:22

标签: angular facebook-javascript-sdk facebook-login

Facebook API中的Angular 6有问题:我无法执行或更改函数FB.api中的变量值

我尝试用从Facebook获得的数据覆盖表单的字段,但是当我想对值进行修补时,我得到了Cannot read property 'patchValue' of undefined

这是我的按钮:

<button type="button" class="btn" (click)="submitLogin();">Login with facebook</button>

component.ts

/* ... angular imports ... */

declare const FB: any;

export class CouponsComponent implements OnInit {

  forma: FormGroup;
  showForm: boolean = false;
  usuario: any;

  /* more code ... */

  ngOnInit() {

    (window as any).fbAsyncInit = function() {
      FB.init({
                appId      : {api-key},
                cookie     : true,
                xfbml      : true,
                version    : 'v3.2'
            });
            FB.AppEvents.logPageView();
    };

    (function(d, s, id){
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/es_LA/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

  }

  submitLogin(){

    FB.login((response)=> {

      if (response.status === 'connected') {        

                FB.api('/me', {fields: 'last_name, name, email'}, function(response) {

                    if (response) {
                        this.usuario = response;

                    this.forma.patchValue({ // -> get Cannot read property 'patchValue' of undefined
                        nombre: this.usuario.name + ' ' + this.usuario.last_name,
                        email: this.usuario.email,
                    })

                        console.log(this.usuario); // -> get fine response
                        console.log(this.forma); // -> get undefined
                    }

                });

                setTimeout(() => {
                    console.log(this.usuario); // -> get undefined
                }, 3000)

            } else {
                console.log('User cancelled login or did not fully authorize.');
            }
      });
  }


}

1 个答案:

答案 0 :(得分:1)

this范围内,

api不再是组件引用。获取组件引用的最佳方法是从submitLogin开始声明cost self = this;,然后再声明this.forma.patchValue,而不是self.forma.patchValue

您也可以代替function(response)来制作(response)=>,这样就不会创建新的作用域,而this将成为一个组成部分。