Parameter decorator

Our last round of decorators will cover the ParameterDecorator function, which taps into parameters located in function signatures. This sort of decorator is not intended to alter the parameter information or the function behavior, but to look into the parameter value and then perform operations elsewhere, such as, for argument's sake, logging or replicating data. The ParameterDecorator function takes the following parameters:

  • Target: This is the object prototype where the function, whose parameters are decorated, usually belongs to a class
  • Key: This is the name of the function whose signature contains the decorated parameter
  • Parameter index: This is the index in the parameters array where this decorator has been applied

The following example shows a working example of a parameter decorator:

function Log(target: Function, key: string, parameterIndex: number) {
var functionLogged = key || target.prototype.constructor.name;
console.log(`
The parameter in position
${parameterIndex} at ${functionLogged} has been decorated`
);
}

class Greeter {
greeting: string;
constructor (@Log phrase: string) {
this.greeting = phrase;
}
}
// The console will output right after the class above is defined:
// 'The parameter in position 0 at Greeter has been decorated'

You have probably noticed the weird assignation of the functionLogged variable. This is because the value of the target parameter will vary depending on the function whose parameters are being decorated. Therefore, it is different if we decorate a constructor parameter or a method parameter. The former will return a reference to the class prototype and the latter will just return the constructor function. The same applies for the key parameter, which will be undefined when decorating the constructor parameters.

As we mentioned in the beginning of this section, parameter decorators are not meant to modify the value of the parameters decorated or alter the behavior of the methods or constructors where these parameters live. Their purpose is usually to log or prepare the container object for implementing additional layers of abstraction or functionality through higher-level decorators, such as method or class decorators. Usual case scenarios for this encompass logging component behavior or managing dependency injection, as we will see in Chapter 5, Enhancing Our Components with Pipes and Directives.

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

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