为什么此方法/gettor在Angular 2服务中被调用X次 [英] Why does this method/gettor get called X times in an Angular 2 service

查看:89
本文介绍了为什么此方法/gettor在Angular 2服务中被调用X次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将HTML组件中的值绑定到服务中的属性.如果私有变量为null,则它需要关闭并从HTTP调用中获取值.

I am trying to bind a value in my HTML component to a property in a service. If the private variable is null then it needs to go off and get the value from an HTTP call.

但是,我注意到,一旦绑定到HTML组件中的属性gettor,它就会触发多次.

However, I noticed that as soon as I bind to the property gettor in my HTML component then it fires multiple times.

我用以下示例简化了示例: 此柱塞

I have simplified the example with: this Plunker

  get Item(): string {
      console.log("Item()", this._item);
      return this._item;
  }

打开控制台,观察"Item()已启动"的多个输出.我希望它只会被击中一次. (结果与方法而不是gettor相同).如果我在click方法中使用Gettor,则只会触发一次.

Open the Console and observe the multiple outputs of "Item() Initiated". I would expect it to only be hit once. (the result is the same with a method instead of a gettor). If I use the Gettor in a click method it only fires once.

推荐答案

这是因为每次在应用程序中发生更改"时,都必须评估html上的绑定值,以便该绑定项的值具有更改后,它将反映到html,从而为您提供了这种神奇的自动更新绑定.在90%的情况下,这可能就是您想要的,因为您不必担心通知angular来更新绑定属性的值.

This is because the value bound on the html has to be evaluated every time something "has changed" in the app so that if the value of the bound item has changed it will be reflected to the html, thus giving you this magical autoupdating binding. This is probably what you want in 90% of the cases, as you don't want to worry about notifying angular to update a value of a bound property.

这就是说,如果您在getter中有一些沉重的逻辑,或者您希望控制何时更新值,则可以将组件changeDetectionStrategy更改为onPush,例如

That being said if you have some heavy logic in the getter, or you prefer to control when the value will be updated you can change the components changeDetectionStrategy to onPush like in this plunker.

@Component({
  selector: 'my-app',
  template: `
    <div><button (click)="_service.ShowItem()">Show Item</button></div>
    <div>{{_service.Item}}</div>
  `,
  providers: [ Service ],
  changeDetection: ChangeDetectionStrategy.OnPush
})

图拉姆

这就像在说:进行更改检测时不要检查此组件,我会告诉您何时进行检查."

This is like saying, "do not check this component when doing change detection, I will let you know when to check it".

然后,您可以使用名为ChangeDetectorRef的服务来标记该组件以进行更改检测.

You then can use a service called ChangeDetectorRef to mark the component for change detection.

对于http,您想要做的是有一个触发器来执行http调用,然后从响应中获取所需的值并将其缓存"在某个位置,以便可以将其绑定到UI.触发条件可能取决于您的情况,例如,各种各样的事物.间隔,递归,按钮等

For http what you want to do is have a trigger to do the http call and then get the value you need from the response and "cache" it somewhere so that you can bind it to the UI. The trigger can be a variety of things depending on your case, eg. interval, recursion, button etc

这篇关于为什么此方法/gettor在Angular 2服务中被调用X次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆