Kurotsuki Kurotsuki - 1 month ago 7
TypeScript Question

Angular: Code execution in lambda does not affect the template

I'm building app using Angular 2 and stumbled on this problem. When performing ajax call, we usually call them in this fashion:

http.post(this.baseUrl + url, data, { headers: headers}).subscribe(
result => {
this.showForm = false;
},
error => {
this.showForm = true;
}
);


The
showForm
is a property of
Component
which indicate when to add/remove the form, i.e: by setting
*ngIf="showForm"
. If I executing that code, when the ajax call is success, the form will be removed from the DOM, and if the call is failed, the form stay. This is the correct behavior.

Things a little different though, when I executing Facebook Login API. As per the tutorial said, the code should be like this:

FB.getLoginStatus(response => {
if (response.status === 'connected') {
this.showForm = false;
}
else {
this.showForm = true;
}
});


When I executed that code, in the condition where the user already logged in to facebook and already signed in on the app (response.status is
'conencted'
), the code will be executing
this.showForm = false;
inside the response lambda. Following previous behavior, this should be removing the form from the DOM.I've tried to debug it on Chrome and
this.showForm = true;
was indeed executed.

The problem is, although that line of code was executed, the form wasn't removed. Only when I execute this exact code twice or thrice, that the form finally notice the value changes and adjust the view accordingly. This makes the user need to click the facebook login button (which will call that
FB.getLoginStatus()
) twice or thrice, before he can actually signed in.

Is there any fix on this? Or does my way of using
FB.getLoginStatus()
was wrong? I need some enlightenment here.

EDIT:
Fixing wrong executed code, where if response.status is
'conencted'
, the code will be executing
this.showForm = false;
, instead of
this.showForm = true;
which I previously wrote.

Answer Source

I think You've messed up something. You wrote:

When I executed that code, in the condition where the user already logged in to facebook and already signed in on the app (response.status is 'conencted'), the code will be executing this.showForm = true;

but in fact it should execute the first block, so this.showForm = false and should hide the form if You have *ngIf="showForm".

If You're sure that the variable is properly being set (proper part of code is executed) but the View itself is not updated, You can try to update the view manually - maybe Angular just didn't detected this change because of Facebook's async callback.

Check this answer to figure out how to run Angular's detection manually.