在 Angular2 中的扩展 RouterOutlet 中导入自定义服务以进行身份​​验证

Importing custom service in extended RouterOutlet in Angular 2 for authentication

我正在尝试在 Angular 2 中设置身份验证,在 the following article (and from 的帮助下 SO) 我设法创建了自己的扩展 RouterOutlet:

export class LoggedInRouterOutlet extends RouterOutlet {
    publicRoutes: any;
    private parentRouter: Router;
    private loginService: LoginService;

    constructor(_viewContainerRef: ViewContainerRef, _loader: DynamicComponentLoader,
        _parentRouter: Router, @Attribute('name') nameAttr: string,
        private loginService: LoginService) {
        super(_viewContainerRef, _loader, _parentRouter, nameAttr);

        this.parentRouter = _parentRouter;
        this.publicRoutes = {
            'login': true
        };
    }

    _canActivate(url: string, admin: boolean) {
        => Checks with my loginService if user is authenticated
    }


    activate(instruction: ComponentInstruction) {
            if (this._canActivate(url, isAdmin)) {
                => Go to desired URL
            } else {
                => Go to login page
            }
    }
}

这段代码的问题是我的打字稿产生了以下错误:

"Duplicate identifier 'loginService'"

我的代码确实按预期运行,我只是不喜欢将打字稿解析为 javascript 时出现打字稿错误。但是,如果我重命名第二个 loginService,我的代码就会中断,我可以找到

TypeError: this.loginService is undefined

在我的控制台中。我想知道是否有人知道如何解决这个问题?

您在 class

中声明了两次 loginService
export class LoggedInRouterOutlet extends RouterOutlet {
    publicRoutes: any;
    private parentRouter: Router;
    // private loginService: LoginService; // <== remove this

并将参数命名为 loginService 而不是 loginService2

constructor(_viewContainerRef: ViewContainerRef, _loader: DynamicComponentLoader,
    _parentRouter: Router, @Attribute('name') nameAttr: string,
    private loginService: LoginService) {
    super(_viewContainerRef, _loader, _parentRouter, nameAttr);

构造函数参数上的 privatepublic 修饰符已经使用此名称声明了 class 属性。无需再次明确声明 属性。