In Angular, you typically use the built-in @Injectable() for dependency injection. But to create a custom decorator for injecting dependencies:
Step-by-step:
Create the custom decorator:
// log-injection.decorator.ts
export function LogInjection() {
return function (target: any, key: string) {
const original = Reflect.getMetadata('design:type', target, key);
Object.defineProperty(target, key, {
get: () => {
console.log(`${key} injected:`, original.name);
return new original();
},
});
};
}
Use it in a class:
import { LogInjection } from './log-injection.decorator';
import { MyService } from './my.service';
class SomeComponent {
@LogInjection()
myService!: MyService;
}