我的角度4应用程序中有一个类(界面),它有很多字段 . 请注意,此类/接口的实例是 immutable
(即永远不会更改成员) .
例如 .
public interface IHaveALotOfFields {
field1: string;
//...
field500: string;
}
此接口通过(单例/应用程序级别提供)服务提供,该服务将类作为成员公开 . 例如 .
@Injectable()
public class MyService {
public translations: ITranslationsProvider;
}
该服务被注入许多组件(几乎所有组件),并且经常在其相应的模板中使用,并且通常也在组件的 ts
部分中使用 . 例如 .
@Component({
template: `Value: {{service.field500}}`
})
export class MyComponent {
public constructor(public service: MyService) {
}
private doSomething(): string {
return this.service.field1;
}
}
现在我的问题:
-
由于变化检测,一个大类(有很多字段)是否会使角度变慢?
-
有没有办法将类标记为"Ignore me on change detection"? (类似于
ChangeDetectionStrategy.OnPush
,但不是为每个组件指定这个,可以在类本身或服务的成员上声明)
请注意,我不想将所有组件的更改检测策略更改为 OnPush
.
1 回答
否 . 角度变化检测执行两个读取类属性的操作:
当前组件的DOM更新
输入绑定更新子组件/指令
对于这些操作,Angular编译器创建了两个函数:
updateRenderer - 读取模板中使用的字段
updateDirectives - 读取输入绑定表达式中指定的字段
这些函数只读取服务中的特定属性 . 以你为榜样
Value: {{service.field500}}
updateRenderer
函数看起来像是一条线:在每个摘要循环上调用这些函数 . 但正如您所看到的,只会从服务中读取相关属性 . 因此,服务上有多少属性并不重要 .
我假设你会监视它并在出现问题时更新答案 . 但是您可能知道可以使用
cd.detach/cd.attach
禁用/启用组件的更改检测 . 您可以从服务中侦听一些信号,并在需要时手动运行cd .以下是您可以阅读的文章列表,以便更好地了解变更检测的机制:
Everything you need to know about change detection in Angular
Angular’s $digest is reborn in the newer version of Angular
The mechanics of DOM updates in Angular
The mechanics of property bindings update in Angular