Angular: lambda 中的代码执行不影响模板

Angular: Code execution in lambda does not affect the template

我正在使用 Angular 2 构建应用程序并偶然发现了这个问题。在进行ajax调用时,我们通常这样调用:

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

showFormComponent的属性,表示什么时候add/remove形式,即:通过设置*ngIf="showForm"。如果我执行该代码,当 ajax 调用成功时,表单将从 DOM 中删除,如果调用失败,表单将保留。这是正确的行为。

不过,当我执行 Facebook 登录时,情况有些不同 API。按照教程所说,代码应该是这样的:

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

当我执行该代码时,在用户已经登录到 facebook 并且已经在应用程序上登录的情况下(response.status 是 'conencted'),代码将执行 this.showForm = false; 在响应 lambda 中。根据之前的行为,这应该是从 DOM.I 中删除表单已经尝试在 Chrome 上调试它并且 this.showForm = true; 确实被执行了。

问题是,虽然执行了那行代码,但表格并没有被删除。只有当我执行这个确切的代码两次或三次时,表单才会最终注意到值的变化并相应地调整视图。这使得用户需要单击 facebook 登录按钮(将调用 FB.getLoginStatus())两次或三次,然后才能真正登录。

有什么解决办法吗?还是我使用 FB.getLoginStatus() 的方式有误?我需要一些启示。

编辑: 修复错误执行的代码,如果 response.status 是 'conencted',代码将执行 this.showForm = false;,而不是我之前写的 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 = true;

但实际上它应该执行第一个块,所以 this.showForm = false 如果您有 *ngIf="showForm",应该隐藏表单。

如果您确定已正确设置变量(执行了适当的代码部分)但视图本身未更新,您可以尝试手动更新视图 - 也许 Angular 只是没有由于 Facebook 的异步回调而检测到此更改。

检查 了解如何 运行 Angular 手动检测。