Angular 2 Resolve Root Component before instantiat

2019-05-25 22:56发布

问题:

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)
    })
})