简体   繁体   中英

What mean by “Side Effects” in Angular2 documentation?

It's not completely clear for me what exactly meaning by "side effects" in Angular2 documentation, for example when talking about this here (Template Syntax section):

Avoid side effects
As mentioned previously, evaluation of a template expression should have no visible side effects. The expression language itself does its part to keep you safe. You can't assign a value to anything in a property binding expression nor use the increment and decrement operators.

Of course, the expression might invoke a property or method that has side effects. Angular has no way of knowing that or stopping you.

The expression could call something like getFoo(). Only you know what getFoo() does. If getFoo() changes something and you happen to be binding to that something, you risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. In general, stick to data properties and to methods that return values and do no more. 

How evaluating of expression may have side effects and how this may have effect to the UI presentation or logic?

It meas that expressions in value bindings should just calculate a value and return it, but they should not modify the status of other variables.

In contrary expressions in event bindings are supposed to cause side effects. This is why Angular runs change detection after an event listener was called.

See also https://en.wikipedia.org/wiki/Pure_function

Like in almost all languages, properties should not cause a change of state or perform any long-running tasks. See for example the Microsoft-Guidelines here: https://msdn.microsoft.com/en-us/library/ms182181.aspx

Taking this overall Guidelines into account, you see the change-tracking code here: http://blog.angular-university.io/how-does-angular-2-change-detection-really-work/

As you can see, the change-detection is quite straight-forward: Check for the equality and set a property called "isChanged" to true, if the values are different.

Now, assume what happens if some properties perform stuff like:

  • Web-API Calls
  • Changing other properties values
  • Not being idempotent

I don't know the exact Code, but the change-tracker should stay as responsive and simple as possible in order to perform so many runs, which is why it is suggested to keep the properties as straight-forward as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM