启动时从后端加载 Angular2 配置 [英] Angular2 load configuration from backend on startup

查看:20
本文介绍了启动时从后端加载 Angular2 配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Angular2 应用程序中,我尝试使用 HTTP 从引导程序的后端加载配置,以便我可以使用提取的数据来创建 Angular 服务.

In my Angular2 app, I'm trying to load configurations from backend on bootstrap using HTTP so that I can use the extracted data for creating angular services.

每当我尝试读取保存在我的配置中的 HTTP 响应时,我总是收到 TypeError: Cannot read property 'url' of undefined 错误.

Whenever I try to read the HTTP response saved in my Config, I always get TypeError: Cannot read property 'url' of undefined error.

似乎只有当整个引导方法完成时,HTTP 请求才会完成,而我的代码尝试在检索之前提取 Observable 响应.

It appears like the HTTP request completes only when the whole bootstrap method finishes, whereas my code tries to extract the Observable response before it is retrieved.

如何修复它以从服务器提取配置并在启动时使用它来创建角度服务?(我想用提取的数据在提供者内部创建服务)

How can I fix it to extract configuration from server and use it to create angular services on startup? (I want to create services inside providers with extracted data)

如果有更好的方法在启动时从服务器提取配置,请发表评论.

Please comment if there is any better way of extracting configuration from server on startup.

我的 ma​​in.ts 看起来像这样:

My main.ts looks like this:

bootstrap(AppComponent, 
    [APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
    .catch(err => console.error(err)
);

configuration.service.ts

@Injectable()
export class ConfigurationService {

    constructor(private http: Http) {
    }

    load() {
        return this.http.get('config/getConfig').map(response => response.json());
    }

}

config.ts

@Injectable()
export class Config {

    public config;

    constructor(public configurationService: ConfigurationService) {
        configurationService.load().subscribe(
            config => this.config = config,
            error => console.error('Error: ' + error)
        );
    }

    get(key: any) {
        return this.config[key];
    }
}

app.component.ts

@Component({
    selector: 'app',
    templateUrl: 'app/app.component.html',
    styleUrls: ['app/app.component.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [MyService]
})
export class AppComponent {

    constructor(public myService: MyService) {
    }

}

my.service.ts

@Injectable()
export class MyService{

    private url;

    constructor(public config: Config) {
        this.url = config.get('url');
    }
}

推荐答案

您可以利用 APP_INITIALIZER 服务在应用程序启动之前重新加载配置:

You could leverage the APP_INITIALIZER service to reload the configuration before application starts:

bootstrap(AppComponent, [
  {
     provide: APP_INITIALIZER,
     useFactory: (config:Config) => {
       return config.load();
     },
     dependency: [ Config ]
   }
]);

为此,您需要稍微调整一下您的 ConfigService 类:

For this, you need to adapt a bit your ConfigService class:

@Injectable()
export class ConfigService {
  constructor(private http:Http) {}

  load() { // <------
    return new Promise((resolve) => {
      this.http.get(...).map(res=>res.json())
        .subscribe(config => {
          this.config = config;
          resolve();
        });
  }
}

然后,您将能够直接访问应用程序中配置对象的属性.

Then you'll be able to access directly properties on the configuration object within your application.

这篇关于启动时从后端加载 Angular2 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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