What is parameters decorator in angular - amresh087/newronaRepos GitHub Wiki
In Angular, parameter decorators are used to annotate and modify the parameters of class constructors and methods. They are primarily used for dependency injection. Here are some common parameter decorators:
@Inject(): This decorator allows you to inject a dependency into a class. It's often used when you need to provide a specific instance or value, especially when working with tokens.
import { Injectable, Inject } from '@angular/core';
import { MY_TOKEN } from './tokens';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@Inject(MY_TOKEN) private myTokenValue: any) {
console.log(myTokenValue);
}
}
@Optional(): This decorator is used to indicate that a dependency is optional. If the dependency is not found, Angular will inject null instead of throwing an error.
import { Injectable, Optional } from '@angular/core';
import { OptionalService } from './optional.service';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@Optional() private optionalService: OptionalService) {
if (this.optionalService) {
this.optionalService.doSomething();
} else {
console.log('OptionalService is not provided');
}
}
}
@Self(): This decorator is used to restrict the injector to look for the dependency only in the current injector, not in any parent injectors.
import { Injectable, Self } from '@angular/core';
import { SelfService } from './self.service';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@Self() private selfService: SelfService) {
this.selfService.doSomething();
}
}
@SkipSelf(): This decorator is used to instruct the injector to look for the dependency in parent injectors only, skipping the current injector.
import { Injectable, SkipSelf } from '@angular/core';
import { ParentService } from './parent.service';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@SkipSelf() private parentService: ParentService) {
this.parentService.doSomething();
}
}
@Host(): This decorator is used to restrict the injector to look for the dependency in the host element's injector only.
Example with Custom Parameter Decorator
You can also create custom parameter decorators to add specific behavior to your parameters. Here's an example:
import { Inject, Injectable } from '@angular/core';
// Custom decorator factory
function LogParameter(target: Object, propertyKey: string | symbol, parameterIndex: number) {
const existingRequiredParameters: number[] = Reflect.getOwnMetadata('log_parameters', target, propertyKey) || [];
existingRequiredParameters.push(parameterIndex);
Reflect.defineMetadata('log_parameters', existingRequiredParameters, target, propertyKey);
}
// Applying the custom decorator
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@LogParameter private message: string) {
console.log(`Message: ${message}`);
}
}