AngularJS2-在应用程序启动之前预加载服务器配置 [英] Angularjs2 - preload server configuration before the application starts

查看:50
本文介绍了AngularJS2-在应用程序启动之前预加载服务器配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular2 RC5.我希望能够在应用启动之前加载服务器的IP地址和其他一些配置参数.如何在最新的RC5中做到这一点?

I am working with Angular2 RC5. I would like to be able to load my server IP address and some other configuration parameters before my app boots up. How can I do this in the latest RC5?

我看过其他文章,但没有帮助:

I have seen other articles, but they are not helpful:

  1. 如何在angular2中预加载配置文件:此处提供的答案特定于webpack.我正在使用systemjs.
  2. https://medium. com/@hasan.hameed/reading-configuration-files-in-angular-2-9d18b7a6aa4#.m8lontnas :这是针对较旧版本的Angular2.不推荐使用某些使用的类.
  1. How to preload a config file in angular2: The answer provided here is specific to webpack. I am using systemjs.
  2. https://medium.com/@hasan.hameed/reading-configuration-files-in-angular-2-9d18b7a6aa4#.m8lontnas: This is for the older version of Angular2. Some of the classes used are deprecated.

任何帮助将不胜感激.

修改

我尝试在我的app.module.ts中按如下方式使用APP_INITIALIZER:

I tried to use the APP_INITIALIZER as follows in my app.module.ts:

    import { NgModule, provide, APP_INITIALIZER }       from "@angular/core";
    import { ConfigService } from "./shared/services/config.service";
    @NgModule({
        declarations: [AppComponent],
        imports: [BrowserModule,
            routes,
            FormsModule,
            HttpModule],
        providers: [AuthService,
            Title,
            appRoutingProviders,
            ConfigService],
        bootstrap: [AppComponent
            , provide(APP_INITIALIZER,
                {
                    useFactory: (config: ConfigService) => () => config.load(),
                    deps: [ConfigService], multi: true
                })]
    })
    export class AppModule { }

这是我的config.service.ts文件:

This is my config.service.ts file:

    import { Config } from "../model/config";

    export class ConfigService {
        constructor() {
        }

        load(): Promise<Config> {
            let config: Config = new Config("localhost", "5050");
            return Promise.resolve(config);
        }
    }

请注意,我最终将重新写入load以实际读取属性或某些此类文件以加载配置.

Note that I will eventually re-write load to actually read a property or some such file to load configuration.

这是config.ts的样子:

This is what config.ts looks like:

export class Config {

    constructor(
        private machine: string,
        private port: string
    ) {
    }

    private base_url: string = "http://" + this.machine +
    this.port + "/";

    public loginURL: string = this.base_url + "login";
}

我遇到了编译错误

public/app/app.module.ts(27,11): error TS2345: Argument of type '{ declarations: (typeof AppComponent ...' is not assignable to parameter of type 'NgModuleMetadataType'.
  Types of property 'bootstrap' are incompatible.
    Type '(typeof AppComponent | Provider)[]' is not assignable to type '(Type | any[])[]'.
      Type 'typeof AppComponent | Provider' is not assignable to type 'Type | any[]'.
        Type 'Provider' is not assignable to type 'Type | any[]'.
          Type 'Provider' is not assignable to type 'any[]'.
            Property '[Symbol.iterator]' is missing in type 'Provider'.

编辑2

我继续下一步.更新ConfigService以使用http.get读取json文件.现在我得到一个错误.这是更新的文件:

I move on to the next step. Update ConfigService to read a json file using http.get. Now I get an error. Here are the updated files:

export class ConfigService {
    private config: Config;
        constructor(private http: Http) {
    }

    load(): Promise<Config> {
            this.http.get("/blah/config.json")
                 .map(res => res.json())
                 .subscribe((env_data) => {
                     console.log(env_data);
                  });
        this.config = new Config("localhost", "5050");
        return Promise.resolve(this.config);
    }

    getConfig(): Config {
        return this.config;
    }
}

这是NgModule类中的providers部分

Here is the providers section in NgModule class

    providers: [AuthService,
    Title,
    appRoutingProviders,
    ConfigService,
    {
        provide: APP_INITIALIZER,
        useFactory: (config: ConfigService) => () => config.load(),
        deps: [ConfigService, Http],
        multi: true
    }],

请注意,在RC6中,我无法导入HTTP_PROVIDERS,因为我收到以下错误消息:不再在http模块中定义它们.这就是为什么我尝试使用Http.

Note that in RC6 I am not able to import HTTP_PROVIDERS since I get the error that these are not defined in the http module anymore. This is why I tried Http.

在运行时,出现以下错误

On runtime, I get following error

(index):27 Error: Error: Can't resolve all parameters for ConfigService: (?).(…)(anonymous function) @ (index):27
ZoneDelegate.invoke @ zone.js:332
Zone.run @ zone.js:225(anonymous function) @ zone.js:591
ZoneDelegate.invokeTask @ zone.js:365
Zone.runTask @ zone.js:265
drainMicroTaskQueue @ zone.js:497
ZoneTask.invoke @ zone.js:437

推荐答案

在您的根模块中提供

{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]}

其中() => promise是一些调用,它们返回一个Promise并解析为所需的值.

where () => promise is some call that returns a Promise that resolves to the desired value.

另请参见如何将从后端渲染的参数传递给angular2引导程序方法

您可以将服务作为依赖项传递,您可以在其中存储结果.

You can pass a service as dependency where you can store the result.

更新

export function loadConfig(config: ConfigService) => () => config.load()

@NgModule({
        declarations: [AppComponent],
        imports: [BrowserModule,
            routes,
            FormsModule,
            HttpModule],
        providers: [AuthService,
            Title,
            appRoutingProviders,
            ConfigService,
            { provide: APP_INITIALIZER,
              useFactory: loadConfig,
              deps: [ConfigService], 
              multi: true }
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }

更新2

> 柱塞示例

这篇关于AngularJS2-在应用程序启动之前预加载服务器配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆