【问题标题】:Why is an expression in my app.component.html called multiple times?为什么我的 app.component.html 中的表达式被多次调用?
【发布时间】:2017-04-14 07:00:02
【问题描述】:

我在 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 "";
  }



}

感谢您的帮助!

【问题讨论】:

  • 通过说“html文件调用”你的意思是xhr请求?
  • html 没有被多次“调用”。 Angular 需要判断点击触发的动作是否改变了 test() 返回的值,从而刷新页面中显示的值。这就是变化检测的全部意义所在,这很正常。

标签: angular angular2-routing angular2-template


【解决方案1】:

Angular 是如何进行模板表达式求值的,

Angular 在每次更改检测后执行模板表达式 循环。变更检测周期由许多异步触发 活动,例如承诺决议、http 结果、计时器事件、 按键和鼠标移动。

阅读更多相关信息here

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    相关资源
    最近更新 更多