【问题标题】:How to avoid cascading ngOnInit?如何避免级联 ngOnInit?
【发布时间】:2017-10-07 00:15:12
【问题描述】:

我有两个具有父子关系的组件。父组件的 ngOnInit 方法检查用户是否登录,如果未登录则导航到登录页面。

class ParentComponent implements OnInit{
    ngOnInit(){
        if(!authService.loggedIn){ 
           //navigate to login screen code
           return;
        }
    }
}

class ChildComponent implements OnInit{
    ngOnInit(){
        /** POINT TO BE NOTED **/
        // this function is also called even if ngOnInit 
        // of parent navigates to different component and returns.
        // do some stuff with userService.token
        // but because token isn't available the calls fail
    }
}

如果父组件想要导航到其他组件,我如何阻止这个级联 OnInit 调用?

【问题讨论】:

    标签: angular angular2-routing angular2-template ngoninit


    【解决方案1】:

    IMO,您不应检查用户是否已登录并离开组件。您应该改为使用 guard 来执行此操作。

    但是,要回答您的问题,您可以使用

    <child *ngIf="isLoggedIn()"></child>
    

    如果用户未登录,这将阻止创建子组件。

    【讨论】:

    • 我知道 URL 保护,但我认为只是从父级的 ngOnInit 返回会起作用,但它不会那样工作。 URL Guarding 肯定是正确的方法,它发生在组件初始化之前的导航期间。非常感谢,伙计。
    猜你喜欢
    • 2012-04-11
    • 2013-01-17
    • 2017-07-20
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多