实例化子组件之前,Angular 2解析根组件 [英] Angular 2 Resolve Root Component before instantiating child components

查看:146
本文介绍了实例化子组件之前,Angular 2解析根组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刷新网络应用程序时,希望它在实例化任何组件或路由之前请求可能登录的用户数据。
如果找到了用户的数据,我想将其注入到我的所有其他子组件都依赖的服务中。

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.

方案:假设我有3个组件,应用程序(ROOT),家庭和关于。
如果将这段代码放在About组件中,我希望它在实例化之前等待20秒,相反,该组件会立即实例化,只有当我离开该组件时,它才会触发该函数,并且我需要等待20秒

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.

推荐答案

实际上有两种方法可以做到这一点。

There are actually two ways to do it.

1)您可以扩展 Router-Outlet 类,并且对于每个活动组件,您可以等待20秒,然后轻松处理singedIn用户数据(可以在单个文件或单个位置中处理)。

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)或在单个组件中,您可以使用 @ CanActivate 钩子并等待20秒钟,当组件被激活时,您可以将shareService(可能包含用户信息对象)注入构造函数中并做进一步的工作。

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.

为此,您可以在组件中使用 @CanActivate 并等待20秒才能启动。

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


如果我将这段代码放在About组件中,我希望它在实例化之前等待
20秒,相反,该组件会立即实例化
...

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

这篇关于实例化子组件之前,Angular 2解析根组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆