簡體   English   中英

在Angular2中的CanActivate中注入服務

[英]Injecting services in CanActivate in Angular2

我正在嘗試為我的路線創建一個auth Guard服務。 在此服務中,我需要注入要用於返回當前登錄用戶的UserAccountService。

這是我的警衛:

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可以很好地注入組件中,它包含在我的app.module

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

可以很好地注入其他服務,例如CookieServiceHttp等,但是UserAccountService存在此問題。

以下是服務的定義:

 @Injectable()
 export class UserAccountService {

   private currentUser: any = {};

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

感謝您的回覆Gunter。 實際上問題出在這一行:

import { UserAccountService } from '../';

我必須從其實際位置而不是從/index文件引用UserAccountService。

只需為canActivate定義服務(如CanActivateTeam )。 如果CanActivateTeam具有構造函數參數,則將從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 {} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM