javascript - Angular 2 登录指令和 location.createComponent

标签 javascript node.js authentication typescript angular

我在我的 Angular 应用程序上实现了一个登录系统。我发现了一个好资源here为了那个原因。但是自定义 RouterOutlet 指令中有一个错误,如下所示:

import { ElementRef, DynamicComponentLoader, AttributeMetadata, Directive, Attribute } from '@angular/core';
import { Router, RouterOutlet, ComponentInstruction } from '@angular/router-deprecated';

import { UserService } from './user.service';

@Directive({
    selector: 'router-outlet'
})

export class LoggedInRouterOutlet extends RouterOutlet 
{
    publicRoutes: Array;
    private parentRouter: Router;
    private userService: UserService;

    constructor(
        _elementRef: ElementRef,
        _loader: DynamicComponentLoader,
        _parentRouter: Router,
        @Attribute('name') nameAttr: string,
        userService: UserService
    ) { 
        super(_elementRef, _loader, _parentRouter, nameAttr);

        this.parentRouter = _parentRouter;
        this.userService = userService;
        this.publicRoutes = [
            '', 
            'login'
        ];
    }

    activate(instruction: ComponentInstruction) {

        if (this._canActivate(instruction.urlPath)) { 
            return super.activate(instruction); 
        }

        this.parentRouter.navigate(['Login']);
    }

    _canActivate(url) {
        return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn()
    }
}

错误是:TypeError:location.createComponent不是函数

我阅读了有关它的内容,问题可能是 _elementRef 是一个 ElementRef 对象,而 super 方法需要一个 ViewContainerRef 对象。但我刚刚开始学习 Angular ,我不知道如何解决这个问题。此外,Angular2 仍在积极开发中,教程中的版本和我的版本(2.0.0-rc.1)之间的情况可能有所变化

最佳答案

写好我的假设让我找到了解决方案:就像导入 ViewContainerRef 而不是 ElementRef 并在构造函数中获取它的实例一样简单:

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

    this.parentRouter = _parentRouter;
    this.userService = userService;
    this.publicRoutes = [
        '', 
        'login'
    ];
}

当然,我不知道我在做什么,但如果它有效......欢迎那些了解自己的东西并想要添加更多细节的人。

关于javascript - Angular 2 登录指令和 location.createComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37862293/

相关文章:

javascript - 使用 express.js 在 POST 上提供静态内容

node.js - Sequelize 不同步 - 插入

authentication - 来自已安装应用程序的 OpenID 身份验证

javascript - 如何在nodejs中使用lodash/下划线找到两个数组之间的差异

javascript - 如果 .catch on Promise 被执行,如何发出第二个请求?

node.js - 将数据添加到 firebase 时,无法在将 header 发送到客户端后设置 header

api - 开源项目但对 API key 保密

sql-server - 如何为 SQL Server 2017 Management Studio 创建新用户

javascript - 如果应用程序打开 2 个 TCP 套接字,是否会在它们之间维护有序属性?

javascript - 未设置 <svg> 上的宽度/高度属性时获取 svg 图形大小