在Angular 4中设置数据后加载路径

时间:2017-12-29 07:14:24

标签: angular promise observable

在我的应用程序中,我有一些在整个应用程序中很常见的数据。 但是视图加载后会填充数据。 例如用户设置,配置文件等数据。  我知道我们可以在视图加载之前使用resolve来加载数据,但是我无法为所有路由添加解析。 因此,当刷新特定路由时,数据不可用,或者在视图加载后来自服务器的响应。

如何做到这一点?

以下是我想要实现的示例代码。 在App.Component.ts中 如果令牌存在,则重定向到请求的页面,否则重定向到登录。

if (token)
{ 
   this.commonServ.loadAppData();
   this._router.navigate([(path == 'login' || path == '') ? 'test' : path]);                     
}
else
   this._router.navigate(['login']);

加载数据方法可以访问一些API并将数据加载到模型中。

例如:

public loadAppData() {

        this.getUserSettings().then(settings => {
            if (settings) {
                //Do Something
            }
        }, error => {

            });



        this.setUserProfile().then(settings => {
          //Do something

        });

    }

来自setUserProfile的数据在视图加载后出现。 怎么办呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

定义一个" shell"在任何其他组件之前加载的组件,并将解析器添加到其中。

应用程序模板

<router-outlet></router-outlet>

外壳组件模板

<pm-menu></pm-menu>

<div class='container'>
    <router-outlet></router-outlet>
</div>

应用路由模块

@NgModule({
    imports: [
        RouterModule.forRoot([
            {
                path: '',
                component: ShellComponent,
                resolve: { data: DataResolver }. // <--- HERE
                children: [
                    { path: 'welcome', component: WelcomeComponent },
                    {
                        path: 'products',
                        canActivate: [AuthGuard],
                        loadChildren: './products/product.module#ProductModule'
                    },
                    { path: '', redirectTo: 'welcome', pathMatch: 'full' },
                ]
            },
            { path: '**', component: PageNotFoundComponent }
        ])
    ],
    exports: [RouterModule]
})
export class AppRoutingModule { }