为什么我的 app.component.html 中的表达式被多次调用?

Why is an expression in my app.component.html called multiple times?

我在 app.component.html 主模板中跟踪了表达式的求值,我发现每次刷新或单击任何页面时,跟踪都恰好出现 5 次。 然后我在 app.component.ts 的 ngOnInit 中放置了一个跟踪,它只按预期执行一次......只有 html 文件中的表达式被多次调用!

主要路线定义:

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  //{ path: '',  component: DashboardComponent },
  { path: 'dashboard',  
    component: DashboardComponent,
    canActivate: [AuthGuard], 
    children:[
      {
        path:'main',
        component: DashMainComponent
      },
      {
        path:'config',
        component: DashConfigComponent
      },
      {
        path:'projects',
        component: DashProjectsComponent
      }
    ]
  },
  { path: 'signin',  component: SigninComponent },
  { path: 'signup', component: SignupComponent },
  { path: 'inventory', component: InventoryComponent },
  { path: 'project', component: ProjectComponent },
  { path: 'timesheet', component: TimesheetComponent },
  { path: 'messaging', component: MessagingComponent },
  { path: 'profile', component: ProfileComponent }
];

html 文件的顶部:

<div id="app">
    {{test}}

app.component.ts:

import { Component, OnInit } from '@angular/core';
import {AuthService} from './auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import {Config} from './config.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {


  constructor(private authService:AuthService, private router:Router) { }
  ngOnInit(){
    console.log("init");
  }

  get test(){
    console.log("test");
    return "";
  }



}

感谢您的帮助!

这是Angular模板表达式求值的方式,

Angular executes template expressions after every change detection cycle. Change detection cycles are triggered by many asynchronous activities such as promise resolutions, http results, timer events, keypresses and mouse moves.

了解更多信息 here

希望对您有所帮助!!