Angular 2 Resolve Root Component before instantiating child components

只谈情不闲聊 提交于 2019-12-22 09:39:51

问题


When I refresh my web-app, I want it to request the potential signed in user's data before instantiating any components or routes. If the user's data was found, I want to inject it into a service, which all my other sub components depend on.

Scenario: Say I have 3 components, App (ROOT), Home & About. If I place this code in my About component, I expect it to wait 20seconds before it instantiate, instead, the component gets instantiated instantly, only when I move away from this component, it triggers the function and I wait 20 sec to reach Home.

routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
    return new Promise((res, rej) => {
        setTimeout(function () {
            res(true);
        }, 20000)
    })
}

Ideally I don't want the resolve to be connected to any route, I want the request the resolve in the root component before I even instantiate any routes.


回答1:


There are actually two ways to do it.

1) Either you may extent Router-Outlet class and for each active component you can wait for 20 secs and easily deal with singedIn users data (both can be handled in single file or single place).

2) OR in individual component you can use @CanActivate hook and wait for 20 secs and when a component becomes activated you can inject shareService(probably contains user information object) into constructor and do further things.

For that you can use @CanActivate in component and wait for 20seconds before it gets initiated.

If I place this code in my About component, I expect it to wait 20seconds before it instantiate, instead, the component gets instantiated instantly...

@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
   return new Promise((res, rej) => {
        setTimeout(function () {
            res(true);
        }, 20000)
    })
})


来源:https://stackoverflow.com/questions/36260780/angular-2-resolve-root-component-before-instantiating-child-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!