【问题标题】:How to override deactive method in Router?如何覆盖路由器中的停用方法?
【发布时间】:2016-07-14 01:26:43
【问题描述】:

我正在尝试使用以下内容覆盖路由器上的 deactive 方法:

导出类 AnimationRouterOutlet 扩展 RouterOutlet { 公共路线:任何; private parentRouter:路由器;

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

    this.parentRouter = _parentRouter;
}

deactivate(instruction: ComponentInstruction){
    setTimeout(()=>{
        console.log("deactivvated state");
        return super.deactivate(instruction);
    },1000);
}

activate(instruction: ComponentInstruction) {
    console.log(instruction);
    return super.activate(instruction);
}

}

如您所见,我正在尝试在更改网页时造成延迟 - 这样我就可以创建一些动画。

但是,使用这个,我有 TypeScript 编译器错误:

:错误 TS2415:“AnimationRouterOutlet”类错误地扩展了基础 类'RouterOutlet'。属性“停用”的类型是 不相容。 类型 '(instruction: ComponentInstruction) => void' 不可分配给类型 '(nextInstruction: ComponentInstruction) => 承诺'。 类型 'void' 不能分配给类型 'Promise'。

我该如何解决这个问题?

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    您不能以这种方式更改被覆盖函数的返回类型。返回类型需要与超类中的返回类型相同或更特殊的类型。

    如果你实现了CanDeactivate,你可以保证路由器在路由离开组件之前会等待。

    【讨论】:

    • 谢谢!我应该覆盖原来的路由器“停用”以增加延迟吗?
    • routerOnDeactivate() 将被添加到组件中,默认支持等待 promise 结算。可能还有其他更通用的方法,但我自己还没有深入研究路由。
    • routerCanDeactivate() 在这里可能是一个更好的选择。它在卸载视图之前等待。
    • @A_Singh 这是我的第一个想法,但routerCanDeactivate 的文档没有提到Promise,而routerOnDeactivate 的文档明确指出返回的Promise 可以解决.
    • 我认为它也返回了一个 Promise see at the end here
    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2016-07-12
    • 2017-01-17
    • 2011-03-31
    • 1970-01-01
    • 2017-12-16
    • 2018-01-06
    相关资源
    最近更新 更多