【问题标题】:Bootstrapping an Angular 2 application with remote data使用远程数据引导 Angular 2 应用程序
【发布时间】:2016-10-29 09:54:57
【问题描述】:

我正在尝试设置一个应用程序,让我的 Angular 客户端应用程序与 API 服务器进行通信。在这个 API 服务器中,我声明了各种环境变量以匹配它的不同环境(当前是 developmentproduction)。

Angular 客户端应该通过 HTTP 获取在 API 端点 http://myserver.com/api/client-config 上提供的这些环境变量的一部分。我知道这应该在应用程序启动之前发生,但我不明白应该在哪里或如何包含 HTTP 调用。

app.module.ts

...
import firebaseConfig from './config/firebase.config'; 

@NgModule({
    declarations: [
        AppComponent,
        VrtVideoPlayer,
        VrtAppsComponent,
        SubtitlesComponent,
        RangeSliderComponent,
        listPipe
    ],
    imports: [
        BrowserModule, 
        FormsModule,
        NgbModule,
        VgCore, 
        VgControlsModule, 
        VgOverlayPlayModule, 
        VgBufferingModule,
        HttpModule,
        AngularFireModule.initializeApp( firebaseConfig() ),
        RouterModule.forRoot([
            { path: 'subtitles', component: SubtitlesComponent },
            { path: '', component: SubtitlesComponent },
        ]),
    ],
    providers: [ExtBrowserXhr],
    bootstrap: [AppComponent],
})
export class AppModule {}

app.component.ts

import {Component} from '@angular/core';

import '../node_modules/bootstrap/scss/bootstrap.scss';
import './common/styles/styles.scss';

@Component({
    selector: 'my-app',
    templateUrl: 'app.component.html',
})
export class AppComponent {
}

bootstrap.ts

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

更具体地说 以下导入:

从'./config/firebase.config'导入firebaseConfig

依赖于 API 服务器环境中声明的环境变量。我可以在这里简单地发出我的 HTTP GET 请求吗?如果我的应用程序需要 http://myserver.com/api/client-config 在其他地方提供的配置对象,这将不是一个理想的解决方案。是否可以使用这些数据引导我的应用程序,如果是这样 - 关于此的最佳做法是什么?

【问题讨论】:

标签: angular webpack bootstrapping angular-module


【解决方案1】:

只是为了回答我自己的问题;在这种特殊情况下,我认为使用环境变量的客户端实现是解决我的问题的正确方法,而不是尝试导入在服务器环境中定义的变量。

我使用 Webpack 运行我的客户端。可以在此处找到实现客户端环境变量的可能方法的完美示例:

angular2-webpack-starter/wiki

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 2016-07-10
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多