Angular2在应用程序引导程序启动之前从服务器端加载api配置显示

时间:2017-06-30 12:20:59

标签: javascript angular api

我正在使用angular 2 web应用程序。在那,我在应用程序bootrap之前从api获取应用程序配置详细信息。为此,我在浏览器上搜索并找出这些链接

How to call an rest api while bootstrapping angular 2 app

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

跟着他们。在angular-cli和浏览器控制台上我没有得到任何错误。但是我的页面在加载文本时显示为空,这是我在加载角度之前显示的。

这是我的代码

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 在这个文件中,我从服务器端加载api配置

        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;
                        });
                }); 
            }
        }

当我在下面的代码中替换load()api服务时,它可以正常工作

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

但是随着api的召唤,它没有。 我发现的是,当我返回它工作的json对象时,但是当我进行api调用时返回promise对象它不会。我不知道如何解决这个问题。

提前致谢。

我的项目有点大,所以我不能放入吸虫

1 个答案:

答案 0 :(得分:0)

尝试使用这样的promise对象:

 load(): Promise<Object> {
        var promise = this.http.get('./app.json').map(res => res.json()).toPromise();
        promise.then(res=> this.label= res);
        return promise;
    }