我正在构建简单的Login Verification指令,它将按照here所述的方式工作。我想做一些调整 - 我想在这样的启动函数中创建新的Provider:
new Provider(RouterOutlet, {
useFactory: (_elementRef: ElementRef, _loader:DynamicComponentLoader, _parentRouter: Router,_authenticationService:AuthenticationService) => new SessionVerificationRouterOutlet(_elementRef, _loader, _parentRouter, _authenticationService),
deps: [ElementRef, DynamicComponentLoader, Router, AuthenticationService]
})
但是,正如你在这里看到的那样:
@Directive({
selector: 'auth-router-outlet'
})
export class SessionVerificationRouterOutlet extends RouterOutlet {
publicRoutes: string[];
private parentRouter: Router;
constructor(
_elementRef: ElementRef, _loader: DynamicComponentLoader,
_parentRouter: Router, @Attribute('name') nameAttr: string, private _authenticationService: AuthenticationService
) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
this._authenticationService = _authenticationService;
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._authenticationService.isLoggedIn()
}
}
我们可以看到,' SessionVerificationRouterOutlet'在构造函数中也使用@Attribute
元素。如何在new Provider(..)
方法中传递必需属性?
答案 0 :(得分:1)
@Attribute
将从该元素的属性(在您的情况下,name
一个)获取该值作为常量。有点喜欢:
<auth-router-outlet name="something"></auth-router-outlet>
无需定义何时创建提供程序...此外,我认为您不需要使用useFactory
来配置自定义路由器插座。以下就足够了:
provide(RouterOutlet, {
useClass: SessionVerificationRouterOutlet
})
答案 1 :(得分:1)
<强>更新强>
要使用自定义<router-outlet>
,只需将其列在组件的指令数组中:
@Component({
...
directives: [ROUTER_DIRECTIVES, SessionVerificationRouterOutlet],
})
确保在ROUTER_DIRECTIVES
全球使用
provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES, SessionVerificationRouterOutlet], multi: true})
<强>原始强>
这也应该这样做:
provide(RouterOutlet, {useClass: SessionVerificationRouterOutlet}),
然后@Attribute()
应该有用。
否则您可以使用@Input()
export class SessionVerificationRouterOutlet {
@Input() name:String;
ngOnInit() {
console.log(this.name);
}
}
但是,只有在调用ngOnInit()
生命周期回调时才会在构造函数中提供该值。