【问题标题】:Using *ngIf causes infinite loop with HTTP request使用 *ngIf 导致 HTTP 请求无限循环
【发布时间】:2017-01-02 19:16:06
【问题描述】:
private login() {
    this.http.get(`http://localhost/api/token/${id}`)
        .map(res => res.json())
        .subscribe(res => {
            this.response = res;
            if (this.response) {
                this.router.navigate(['/']);
            } else {
                console.log('access denied');
                return false;
            }
        });
}
<p *ngIf="!login()">Wrong password or username</p>

一切都正确编译,但是当我刚刚启动应用程序时,一个无限循环开始了,将数百个access denied 日志发送到控制台。这是令人难以置信。 &lt;p&gt; 在屏幕上可见。

为什么会这样?单击login 按钮时正在调用登录函数。我不必单击它来启动无限循环。它只会在应用出现在浏览器中时发生。

【问题讨论】:

  • 可能*ngIf 位于*ngFor 循环内?
  • @5313M 我不这么认为,伙计
  • 显示更多代码。你没有提到你从哪个组件调用登录。显示你的 console.log(res);你的路由文件。当您不返回 true 或 false 时,您正在调用一个函数,它可能返回 null 或 false 所以!会变成真的。
  • 为什么难以置信? Angular 必须不断调用该方法来确定它是否仍应显示关联的元素。它会在每一个tick调用该方法,看看是否需要更新页面的状态。
  • @H.Doe 反其道而行之;而不是直接调用该方法的元素,获取 组件 来调用该方法并使用结果设置一个布尔字段(例如userIsLoggedIn)。该元素只使用该字段:&lt;p *ngIf="!userIsLoggedIn" ....

标签: javascript angular typescript xmlhttprequest


【解决方案1】:

ngIf 语句定期检查登录方法的状态返回值:这就是登录方法实际上被调用 n 次的原因。不要将 ngIf 绑定到 login 方法的返回值,而是将语句绑定到一个由 login 方法更改的布尔变量:这将阻止该方法被触发,并且观察者将对变量状态进行操作。例如,在您的控制器中...

public authError: boolean = false;

private _login() {
    this.http.get(`http://localhost/api/token/${id}`)
        .map(res => res.json())
        .subscribe(res => {
            this.response = res;
            if (this.response) {
                this.router.navigate(['/']);
            } else {
                console.log('access denied');
                // In case of error, set the auth error property to true
                this.authError = true;
                return false;
            }
        });
    }

在您的模板中:

<p *ngIf="authError">Wrong password or username</p>

请注意我更改了登录方法的名称:私有方法按照惯例应该以下划线开头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2011-07-31
    • 2018-03-12
    • 2017-10-17
    • 2018-05-06
    • 2011-04-06
    相关资源
    最近更新 更多