简体   繁体   中英

Injecting services in CanActivate in Angular2

I am trying to create an auth Guard service for my routes. In this service I need to inject the UserAccountService I am using to return the current logged in user.

This is my guard:

import { Injectable, Inject } from '@angular/core'; 
import { CanActivate } from '@angular/router'; 
import { UserAccountService } from '../';


@Injectable() export class ClaimsGuardService implements CanActivate
{ 
   constructor(private user: UserAccountService) {    }

   canActivate(route, state) {
       return true;   
   } 
}

UserAccountService works fine injected in components, it is included in my app.module :

providers: [
  provideInterceptorService([
    new ServerURLInterceptor(new CookieService())
  ]),
   ClaimsGuardService,
   CookieService,
   UserAccountService,
],

Other services, such as CookieService , Http , etc, are injected just fine but the UserAccountService has this issue.

Below is the definition of the service:

 @Injectable()
 export class UserAccountService {

   private currentUser: any = {};

   constructor(private cookieService: CookieService, private http: InterceptorService) {
   }
 }

Thanks for your reply Gunter. Actually the problem was at this line:

import { UserAccountService } from '../';

I had to reference the UserAccountService from its actual location rather than from the /index file.

Just define a service for canActivate (like CanActivateTeam ). If CanActivateTeam has constructor parameters they will be passed from DI.

https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html

 @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamCmp, canActivate: [CanActivateTeam] } ]) ], providers: [CanActivateTeam, UserToken, Permissions] }) class AppModule {} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM