I was working on a project and came across a service which does not have the @Injectable() decorator, and works fine. Till now , I was under the impression that in angular if we want to implement DI we must use the @injectable() decorator and configure it with the provider. Configuring the service with a provider is mandatory, but it seems using @injectable() decorator is not. It is being used only in some services. The only difference I have noticed in the services using the decorator and the ones that don't is that the former have some dependencies themselves, while the latter don't
I have two types of services:
Type1:
export class SharedService {
//do something
}
Type2:
@Injectable()
export class MainCreditService {
constructor(private http: Http, private config: Config) {
this.config.EndPoints.subscribe(endpointObj => {
this.environment = endpointObj;
});
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule} from '@angular/common/http'
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
],
exports: [],
providers: [MainService,SharedService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { MainService } from '../../services/main.service';
import { SharedService } from '../../services/shared.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private mainservice: MainService, private sharedService:
SharedService) {
//doSomething
}
Why does one need @Injectable() and the other doesn't
I have watched a few videos on DI and gone through some articles, but still having a hard time understanding that where should we use this decorator and why. Can someone please explain the purpose of this decorator or maybe paste links to sources that have explained it well.