我在我的 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/