Javascript Angular 2登录指令和location.createComponent
我在angular应用程序上实现了一个登录系统。我找到了一个很好的资源。但是自定义RouterOutlet指令中有一个错误,如下所示:Javascript Angular 2登录指令和location.createComponent,javascript,node.js,login,typescript,angular,Javascript,Node.js,Login,Typescript,Angular,我在angular应用程序上实现了一个登录系统。我找到了一个很好的资源。但是自定义RouterOutlet指令中有一个错误,如下所示: import { ElementRef, DynamicComponentLoader, AttributeMetadata, Directive, Attribute } from '@angular/core'; import { Router, RouterOutlet, ComponentInstruction } from '@angular/rout
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不是函数
我读了一些关于它的东西,问题可能是\u elementRef
是一个elementRef对象,而super方法需要一个ViewContainerRef
对象。但我刚刚开始学习角度,我不知道如何解决这个问题。此外,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'
];
}
当然我不知道我在做什么,但如果它起作用。。。欢迎那些了解自己的内容并希望在此基础上添加更多细节的人。你做得对-如果需要ViewContainerRef
,只需传递它即可。为了澄清,我将重命名变量!