如何在提供函数中将Attribute作为依赖项传递?

时间:2016-05-09 07:28:34

标签: angular angular2-routing

我正在构建简单的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(..)方法中传递必需属性?

2 个答案:

答案 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()生命周期回调时才会在构造函数中提供该值。