I don't understand When to use @Inject and when to use @Injectable ?
import {Component, Inject, provide} from '@angular/core';
import {Hamburger} from '../services/hamburger';
export class App {
bunType: string;
constructor(@Inject(Hamburger) h) {
this.bunType = h.bun.type;
}
}
And..
import {Injectable} from '@angular/core';
import {Bun} from './bun';
@Injectable()
export class Hamburger {
constructor(public bun: Bun) {
}
}
We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. We use the @Injectable class decorators to automatically resolve and inject all the parameters of class constructor.
The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.
The Typed Inject project focuses on type safety and explicitness. It uses neither decorators nor decorator metadata, opting instead for manually declaring dependencies. It allows for multiple DI containers to exist, and dependencies are scoped either as singletons or as transient objects.
4.1. The @Inject annotation lets us define an injection point that is injected during bean instantiation. Injection can occur via three different mechanisms. A bean can only have one injectable constructor.
The @Injectable
decorator aims to actually set some metadata about which dependencies to inject into the constructor of the associated class. It's a class decorator that doesn't require parameters. Without this decorator no dependency will be injected...
@Injectable()
export class SomeService {
constructor(private http:Http) {
}
}
The @Inject
decorator must be used at the level of constructor parameters to specify metadata regarding elements to inject. Without it, the type of parameters is used (obj:SomeType
is equivalent to @Inject(SomeType) obj
).
@Injectable()
export class SomeService {
constructor(@Inject(Http) private http:Http, @Inject('sometoken') obj) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With