Search code examples
angularangular2-services

Declaring services in providers of multiple components


I am new to angular 2 and I'm working on it for a week or so. As per the best coding practices followed by our team, we declare our services in the providers of the root component.

I wonder, what if we declare our services in providers of multiple components?


Solution

  • Adding a service to the component provider will override the parent provider and will create a new instance of that service

    here is an example i will assume that i have service called MyService

    app.module.ts

    @NgModule({
        ....,
        imports: [MyService, ...]
    })
    

    MyComponent1.ts

    @Component({
        ...,
        providers: [MyService]
    })
    
    export default class MyComponent1 {
        constructor(private Myservice myService) {
    
        }
    }
    

    MyComponent2.ts

    export default class MyComponent2 {
        constructor(private Myservice myService) {
    
        }
    }
    

    myService in MyComponent1 and MyComponent2 are totally different

    the one in MyComponent1 is that one that was provided from the MyComponent1 itself unlike the one in MyComponent2 it's the one that was provided from app.module