Using decorators

Decorators are functions that modify a class, property, method, or method parameter. The following example illustrates how to define and use a simple decorator that adds a static parameter to the class:

// decorator function
function AddMetadata (...args) {
  return function (target){
    target.metadata = [...args];
  }
}

// decorator applied
@AddMetadata({ metadata: 'some values'})
class Model {
}

The three dots syntax (...) is the spread operator, which is a feature of JavaScript 2015 that deconstructs the items of a given array.

Decorators versus annotations

You might have heard the term annotations; they are simply metadata related to Angular 2. Before the Angular team decided to use TypeScript, they introduced us to a new language that they called AtScript. This language included a feature called annotations, which look exactly like decorators. So what's the difference? The decorator is an interface for creating those Angular annotations. Decorators are executed and in Angular 2, they have the responsibility to set metadata leveraging the Reflect Metadata library. Furthermore, decorators are a proposal for ES7—the next version of JavaScript. For that reason, we can focus on decorators.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.91.44