小编Ale*_*kov的帖子

Angular2 模板表达式在更改检测时为每个组件调用两次

相当标准的情况。

有一个父组件<item-list>。在其模板内*ngFor生成了 20 个子组件<item-block>[ngStyle]使用调用 function 的指令和模板表达式设置子组件样式setStyles()

问题(或可能不是)是,当在一个特定子元素上发出任何事件时,表达式setStyles()会对每个子组件执行两次。

因此,如果我们单击示例中的一个特定项目,并且我们有 20 个<item-block>组件 -setStyles()将执行 20+20 次。

问题是

  1. 为什么会发生这种情况以及这是预期的行为吗?
  2. 它如何影响性能
  3. 如何避免这种情况 - 每个子组件/检测更改仅调用一次。

示例&plnkr

plnkr(单击项目 - 打开控制台以进行调试输出)

import {Component} from '@angular/core'

@Component({
  selector: 'item-list',
  template: `
    <item-block
        [item]="item"
        *ngFor="let item of items"
    ></item-block>
  `,
})
export class ItemListComponent {

  items: any[] = [];

  constructor() {}

  ngOnInit() {
     // generate dummy empty items
    for (let i = …
Run Code Online (Sandbox Code Playgroud)

angular2-template angular2-changedetection angular2-components angular

5
推荐指数
1
解决办法
1685
查看次数

有角度的。使用APP_INITIALIZER时路由器DI不起作用

我正在通过APP_INITIALIZER以下方式从服务器预加载应用程序配置AppModule

providers: [
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: configServiceFactory,
      deps: [ConfigService],
      multi: true
    }
  ],
Run Code Online (Sandbox Code Playgroud)

然后,ApiService从手动注入ConfigService

@Injectable()
export class ConfigService {

  private api: ApiService;

  public constructor(
    private injector: Injector
  ) {

    // Avoid cyclid dependencies, inject manually:
    this.api = injector.get(ApiService);
  }
Run Code Online (Sandbox Code Playgroud)

最后router在注入时是不确定的ApiService

import { Http, Headers, RequestOptionsArgs, Response } from '@angular/http';
import { Router } from '@angular/router';

@Injectable()
export class ApiService {

  constructor(
    private router: Router,
    private http: Http …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-di angular

5
推荐指数
1
解决办法
1955
查看次数