3

I need to make two HTTP call one after another before angular initialize. Is there any way to initialize angular 2 synchronously?

Please do not say our app should work asynchronously. I am working on generic build using "angular-cli" . First i need to fetch the environment which is set in a json file and on the basis of that environment i need to load configuration. So i need two HTTP calls.

{ 
provide: APP_INITIALIZER,
   useFactory: (config: AppConfig) => () => config.load(),
   deps: [AppConfig], multi: true
}

Inside load() i have two http call one inside other but before two call get completed angular is initialized.

2

1 Answer 1

3

You're on a correct way. You can make both http calls into config.load() function.

 public load() {
    return new Promise((resolve, reject) => {
        this.http.get('first.json').map( res => res.json() ).catch((error: any):any => {

            console.error('Error at first call');

            resolve(error);
            return Observable.throw(error.json().error || 'Server error');
        }).subscribe( (firstResponse) => {

            let request = this.http.get('second.json');

            request
                .map( res => res.json() )
                .catch((error: any) => {
                    console.error('Error at second call');
                    resolve(error);
                    return Observable.throw(error.json().error || 'Server error');
                })
                .subscribe((secondResponse) => {

                    //Here i have both
                    firstResponse, secondResponse

                    resolve(true);
                });

        });

    });
}

Consider the fact that functions and lambdas are not supported to useFactory anymore, so you have to rewrite it little bit. Also make sure that you provide your AppConfig

function initialConfigLoad(config: AppConfig) {
    return () => config.load();
};

providers: [
    ...
    AppConfig, // <- Provide AppConfig
    {
        provide: APP_INITIALIZER,
        useFactory: initialConfigLoad,
        deps: [AppConfig],
        multi: true
    }
]
Sign up to request clarification or add additional context in comments.

1 Comment

Note that the most important part of this piece of code is the call to resolve(true); in the Promise. It signals to Angular that it can continue with the app initialization.

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.