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.');
}
});
}
}
答案 0 :(得分:1)
this
范围内, api
不再是组件引用。获取组件引用的最佳方法是从submitLogin
开始声明cost self = this;
,然后再声明this.forma.patchValue
,而不是self.forma.patchValue
。
您也可以代替function(response)
来制作(response)=>
,这样就不会创建新的作用域,而this
将成为一个组成部分。