我刚刚发现我已经创建了一个新的 angular 7 项目,并且我在 app.component.ts 中使用以下代码创建了一个方法。
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angular-test';
constructor() {}
prueba(){
console.log('Hello World!');
}
}
然后在 app.component.html 我调用该方法,附加代码。
app.component.html
{{prueba()}}
发生这种情况是因为您在这样的表达式上调用 test() 函数:
如果你使用这样的表达式,这个函数至少会被调用两次。
原因是 Angular 会执行摘要循环,直到所有内容都更新(因此至少会更新两次)。在您的情况下,它将第一次运行以返回值,第二次运行以检查剩余的任何更改。
以这种方式调用函数不是好的做法。
多次执行console.log的原因是因为角度停止的变化。在这里,他更深入地解释了它。
https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
您尝试执行该功能的方式不正确。
如果你希望它在你启动 web 时立即执行,你必须使用方法
ngOnInit()
一切顺利
我想知道在它从 ngOninit 执行但它继续执行很多次的情况下会发生什么我有来自服务的响应我没有调用我的方法 {{function()}} 但来自 NgOnInit 但它持续加载数百次,本地只调用1次但在服务器上多次