本文介绍了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 个组件,App (ROOT)、Home &关于.如果我将此代码放在我的 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.

推荐答案

其实有两种方法.

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 秒,组件得到立即实例化...

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

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

05-20 18:27