2

I have an app where i want to load all the messages from the server before actually loading the app.

I've put the http request in my app component in OnInit.

but I don't have a way to make the routing "wait" before fetching the first page and the application is starting with empty messages.

Any way to do this ?

2 Answers 2

4

You can use the APP_INITIALIZER for this:

Add this to the providers array of your AppModule:

{provide: APP_INITIALIZER, useFactory: appInitFactory, deps: [MsgLoader], multi: true}

Then create a function factory which obtains your messages. This should return an arrow function returning the actual Promise:

export function appInitFactory(msg: MsgLoader): () => Promise<any> {
    return () => msg.loadMessages();
}

If you don't mind that the AppComponent loads, but do mind about its subpages being loaded, you can use the initialNavigation property on your root routing:

RouterModule.forRoot(AppRoutes, {initialNavigation: false})

This prevents loading of the first module. You should however have some service injected into your AppComponent which handles the loading of your messages, and then routes to the required module

Sign up to request clarification or add additional context in comments.

Comments

1

A simple solution:

When you define your routes, add a prehome page and PreHomeComponent:

 imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'prehome', pathMatch: 'full' },
            { path: 'prehome', component: PreHomeComponent },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: "job/:id", component: JobComponent },
            { path: '**', redirectTo: 'prehome' }
        ]),
        MaterialModule
    ]    

in your PreHomeComponent load your required messages from the server and then redirect to home.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.