Angular 无法在 FB.api() 中调用函数

Angular Cant call function inside of FB.api()

我在 Angular 6 中遇到 Facebook API 的问题:我无法执行或更改函数内变量的值 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.');
            }
      });
  }


}

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

您也可以代替 function(response) make (response)=> 这样它不会创建新的作用域并且 this 将成为一个组件。