Load route after data is set in Angular 4

佐手、 提交于 2020-01-13 06:56:06

问题


In my application, I have some data that is common throughout the application. But the data is populated after the view loads. For example data such as user-settings, profile etc. I know we can use resolve for loading data before the view loads, but I cant add resolve to all the routes. So when a specific route is refreshed the data is not available or the response from the server comes after the view loads.

How can this be done?

Below is the sample code of what I'm trying to achieve. in App.Component.ts if the token exists then redirect to the requested page else redirect to login.

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

The load data method hits a few API's and loads data to models.

for example:

public loadAppData() {

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

            });



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

        });

    }

The data from setUserProfile comes after the view has loaded. How can this be done?

Thanks!


回答1:


Define a "shell" component that is loaded before any of the other components and add the resolver to it.

App Template

<router-outlet></router-outlet>

Shell Component Template

<pm-menu></pm-menu>

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

App Routing Module

@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 { }


来源:https://stackoverflow.com/questions/48018921/load-route-after-data-is-set-in-angular-4

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