0

I am using the angular 2 web app. In that, i am getting app configuration details from the api before the app bootsrap. For that i searched on the browser and find out these links

How to call an rest api while bootstrapping angular 2 app

https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9

And followed them. In the angular-cli and also on the browser console i didn't get any error. But my page comes empty with loading text, that was i displayed in the before loading angular.

Here is my code

app.module.ts

    import { BrowserModule }                   from '@angular/platform-browser';
    import { NgModule, APP_INITIALIZER }       from '@angular/core';
    import { FormsModule }                     from '@angular/forms';
    import { HttpModule, Http}      from '@angular/http';
    import { SocketIoModule, SocketIoConfig }  from 'ng2-socket-io';
    import { SharedModule }                    from './shared/shared.module';
    import { TranslateModule, TranslateLoader} from '@ngx-translate/core';
    import { TranslateHttpLoader}              from '@ngx-translate/http-loader';
    import { AppRoutingModule }                from './app.route';
    import { AppComponent }                    from './app.component';
    import { ChatComponent }                   from './chat/chat.component';
    import { ChatService }                     from './chat/chat.service';
    import { AddressComponent }                from './address/address.component';
    import { HomeComponent }                   from './home/home.component';
    import { SettingService }                  from './shared/service/api/SettingService';
    import { FilterByPipe }                    from './filterPipe';
    import { Ng2ScrollableModule }             from 'ng2-scrollable';
    import { AppConfig }                       from './app.config';

    import {Injectable}                        from '@angular/core';
    import {Observable}                        from 'rxjs/Rx';

    const config: SocketIoConfig = { url: 'http://192.168.1.113:7002', options: {} };

    export function HttpLoaderFactory(http: Http) {
        return new TranslateHttpLoader(http, "http://192.168.1.114:7001/frontend-translation/", "");
    }

    export function SettingServiceFactory(setting: SettingService) {
        return () => setting.load();

        //return true;
    }

    @NgModule({
        declarations: [
            AppComponent,
            ChatComponent,
            AddressComponent,
            HomeComponent,
            FilterByPipe
        ],
        imports: [
            BrowserModule,
            FormsModule,
            HttpModule,
            AppRoutingModule,
            Ng2ScrollableModule,
            SocketIoModule.forRoot(config),
            SharedModule,
            TranslateModule.forRoot({
                loader: {
                    provide   : TranslateLoader,
                    useFactory: HttpLoaderFactory,
                    deps      : [Http]
                }
            }),
        ],
        providers: [
            ChatService,
            AppConfig,
            SettingService,
            { 
                provide   : APP_INITIALIZER, 
                useFactory: SettingServiceFactory,
                deps      : [SettingService], 
                multi     : true 
            }
            /*SettingService,
            {
                provide   : APP_INITIALIZER,
                useFactory: (setting:SettingService) => () => setting.load(),
                //deps      : SettingService,
                multi     : true
            }*/
        ],
        bootstrap: [AppComponent]
    })

    export class AppModule { }

SettingService.ts In this file, i am loading the api configuration from the server side

        import {Injectable} from '@angular/core';
        import {Http, Response} from '@angular/http';
        import {Observable} from 'rxjs/Rx';

        @Injectable()

        export class SettingService {
            public setting;

            constructor(private http: Http) {}

            /**
             * Retrieves the setting details of the website
             * @return {Object} language tranlsation
             */
            public load() 
            {
                return new Promise((resolve, reject) => {
                    this.http
                        .get('http://192.168.1.114:7001/settings')
                        .map( res => res.json() )
                        .catch((error: any):any => {
                            console.log('Configuration file "env.json" could not be read');
                            resolve(true);
                            return Observable.throw(error.json().error || 'Server error');
                        })
                        .subscribe( (envResponse) => {
                            this.setting = envResponse;
                        });
                }); 
            }
        }

When i replace the load() api service within below code it works fine

    public load() {
        return {
            "test": "works well"
        }
    }

But with api call, it doesn't. What i found was, when i am returning the json object it works, but when i am making api call return the promise object it won't. I don't know how to solve this.

Thanks in advance.

My project was little bigger, so i can't put in plunker

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Sivabalan
  • 971
  • 2
  • 18
  • 43

1 Answers1

0

Try to use promise object like this:

 load(): Promise<Object> {
        var promise = this.http.get('./app.json').map(res => res.json()).toPromise();
        promise.then(res=> this.label= res);
        return promise;
    }
Vignesh
  • 2,378
  • 3
  • 25
  • 48