Search code examples
angularsingletonangular2-routingangular2-servicesangular2-guards

How to make Angular2 Service Singleton....again


Please allow me to ask this question again on how to make a singleton service in angular2. I am trying to implement an auth guard with an authentication service being injected.

However, the constructor for the injected services always gets invoked whenever i visit the route being protected by the auth guard. i.e. both "console.log("authgaurd created")" and "console.log("auth services created");" in the snippet below gets invoked every time instead of once.

I've followed the guidelines proposed in similar questions including: How to make Angular2 Service singleton?

But it looks like I may be missing something...help?

Using @angular/core": "^2.3.1

//app.module.ts

import {AuthService} from "./auth.service";
import { AuthGuard } from './auth-guard.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [ 
    QAModule,
    AppRoutingModule,
  ],
  providers: [AuthService,AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

Services

//auth.service

@Injectable()
export class AuthService {

    constructor() {

        console.log("auth services created");
    }
}


//auth-guard.service

@Injectable()
export class AuthGuard implements CanActivate {

    constructor( authService: AuthService) {

        console.log("authgaurd created");

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean  {
        return true;
    }

}

Module and route being protected

//qa-routing.module.ts

const routes: Routes = 
[
  { 
    path: 'qa',      
    component: QAComponent,
    canActivate: [AuthGuard],

  }

];

@NgModule({

  imports: [
   RouterModule.forChild(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class QARoutingModule { }


//qa.module.ts

@NgModule({
  imports: [
    QARoutingModule
  ],
  declarations: [
    QAComponent
  ],
  providers: [ ]
})
export class QAModule {}

Solution

  • umm...yea, so the real issue:

    i am using bootstrap nav bars and using href for the link. Which in turn reloads the context every time i click on the link, giving new injected service. Changed the linking logic to use router.navigate to resolve.