【问题标题】:using a function in *ngIf runs several times instead of once在 *ngIf 中使用函数会运行多次而不是一次
【发布时间】:2018-06-20 21:35:41
【问题描述】:

模板

<pre *ngIf="isAdmin()">{{email|json}} - {{user|json}}</pre>

组件

isAdmin() {
    console.log('isAdmin: ', this.bcAuthService.isAdmin());
    return this.bcAuthService.isAdmin();
}

服务

isAdmin() {
    return this.admins.includes(localStorage.getItem("email"));
}

问题

组件中的函数不断打印几次。为什么?这是错的吗?有什么更好的方法?

【问题讨论】:

  • 模板方法几乎总是会被多次调用。 *ngFor 也是如此,它被迭代多次。如果你有执行昂贵调用的东西,那么你应该缓存结果并在方法中返回,或者使用 ngOnInit 来检索/计算值并将它们设置在你的组件中。

标签: angular


【解决方案1】:

模板方法几乎总是会被多次调用。 *ngFor 也是如此,它被迭代多次。如果你有执行昂贵调用的东西,那么你应该缓存结果并在方法中返回,或者使用 ngOnInit 检索/计算值并将它们设置在你的组件中。

模板代码

<pre *ngIf="isAdmin">{{email|json}} - {{user|json}}</pre>

组件

export class MyComponent implements OnInit {

    isAdmin: boolean;

    ngOnInit() {
        this.isAdmin = this.bcAuthService.isAdmin();
        console.log('isAdmin: ', this.isAdmin);
    }
}

【讨论】:

  • 我按照你的建议做了同样的事情。
【解决方案2】:

找到这个why *ngIf in angular 2 always is executing when use function?之后

我解决了这个问题

组件

ngOnInit() {
    this.is_admin();
}
is_admin() {
    this.isAdmin = this.bcAuthService.isAdmin();
}

html

<pre *ngIf="isAdmin">{{email|json}} - {{user|json}}</pre>

【讨论】:

    【解决方案3】:

    现在您没有方法(取而代之的是成员)并且它没有发送垃圾邮件“isAdmin:true”,但这并不意味着问题已解决。

    您可以对组件的changeDetectionChangeDetectorRef感兴趣 当isAdmin 更改为更新模板(detectChanges)时,实际告诉角度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2019-11-07
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多