Angular 2 – Using a shared service from two locations is a bad idea

Recently I found my way to Angular 2. I am playing around with a couple of components and a shared service in between them to send data back and forth.

I have to say, this was quite a challenge to set up…

For future reference: Don’t define a service as provider in multiple places!!!!!

I had this in app.module.ts

@NgModule({
    imports:      [
        BrowserModule,
        UserModule,
        AppRoutingModule,
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        PageNotFoundComponent,
    ],
    bootstrap:    [ AppComponent ],
    providers:    [
        AuthService,
        UserService,
    ]
})

and this in loginForm.component.ts:

@Component({
    moduleId: module.id,
    selector: 'login-form',
    providers: [
        AuthService
    ],
    templateUrl: 'loginForm.component.html',
})

Thus the shared AuthService was initialized every time I switched between login and the app itself instead of saving the logged in user.

Leave a Reply