Angular: Service injection in Angular

1- Injecting service at project/application level:

@Injectable({
providedIn: 'root'
})
export class TestService {
MyServiceMethodDoesNothing(): void {
}
}

2- Injecting service at a module level:

There are two methods of doing this:

1- First method:

In this method, we provided the name of the module in providedIn property:

@Module({

})
export class TestModule {
}

@Injectable({
providedIn: TestModule
})
export class TestService {
MyServiceMethodDoesNothing(): void {
}
}

2- Second method:

In this method, we don’t set any value to providedIn project in Injectable decorator, instead, we add the class name in the providers property array in Module decorator.

@Injectable()
export class TestService {
MyServiceMethodDoesNothing(): void {
}
}
@Module()
export class TestModule {
providers: [TestService]
}

3- Injecting service at a component level:

To inject a service at the component level, instead, we add the class name in the providers property array in the Component decorator.

@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
providers:[TestService]
})
export class TestComponent {
constructor(private testService: TestService){
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store