nicogaldo
nicogaldo

Reputation: 585

Angular Cant call function inside of FB.api()

I have a problem with Facebook API in Angular 6: I can not execute or change the value of a variable inside the function FB.api

What I try is to overwrite the fields of the form with the data obtained from facebook, but when I want to patch the values I get Cannot read property 'patchValue' of undefined

This is my button:

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

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


}

Upvotes: 1

Views: 706

Answers (1)

karoluS
karoluS

Reputation: 3218

this is not a component reference anymore in api scope. Best way to get component reference is to at the start at the submitLogin declare cost self = this; and later instead of this.forma.patchValue call self.forma.patchValue.

You can also instead of function(response) make (response)=> this way it will not create a new scope and this will be a component.

Upvotes: 2

Related Questions