来自服务的Angular Access数据 [英] Angular Access data from Service

查看:100
本文介绍了来自服务的Angular Access数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular 5和httpclient.我不是内置环境的忠实拥护者来设置我需要使用的环境api URL.我已经切换到使用nginx.conf,在该处我进行了api调用,该API返回的json带有从环境变量设置的api URL.

I'm using angular 5 and httpclient. I'm not a big fan of the built in environments to set up my environment api url's that I need to consume. I have switched to using an nginx.conf where I make an api call that returns a json with my api urls that is set from an environment variable.

我有一项服务,正在进行http.get调用以获取json配置文件.

I have a service where I'm making an http.get call to grab the json config file.

@Injectable()
export class ConfigurationService {
private baseUrl = 'https://someUrl.com';

constructor( private http: HttpClient ) {

}

getConfig(): Observable<any> { 
  return this.http
  .get(this.baseUrl + '/config')
  .map(res=>res);   
};
}

当应用程序首次启动时,将从我的app.component.ts中调用此服务.

This service is called from my app.component.ts when the application first starts.

我有一个constants.ts文件,我想使用它来引用我的api网址

I have a constants.ts file that I want to use to reference my api urls

export class Constants {    

public api1 = //NEED API1 URL FROM SERVICE HERE;
public api2= //NEED API2 URL FROM SERVICE HERE;

从服务中引入数据的最佳方法是什么?我的常量文件不是一个组件,而只是一个类.

What is the best way to bring in the data from the service? My constants file is not a component just a class.

推荐答案

对于这种情况,您应该使用应用程序初始化程序服务.应用程序初始化程序将在应用程序中的所有其他内容之前运行,并且只有完成后,您的应用程序才会加载.它的结构如下:

For something like this you should use an app initializer service. An app initializer runs before everything else in your application and your app won't load until it's done. It's structured like this:

import { Injectable, APP_INITIALIZER } from '@angular/core';

export interface AppConfig {
    api1: string;
    api2: string;
}

@Injectable()
export class ConfigService {
  protected config: AppConfig;

  constructor(private _http: HttpClient) {
  }

  getConfigData(): Observable<any> {
    return this._http.get<AppConfig>('... your config url...')
      .catch(error => {
        alert('Unable to read configuration file:' + JSON.stringify(error));
        return Observable.throw(error);
      });
  }

  public load() {
     return new Promise((resolve, reject) => {
       this.getConfigData()
         .subscribe(
           config => {
             this.config= config ;
             resolve(true);
           },
           err => resolve(err)
         );
     });
  }
}

export function ConfigServiceInitFactory(configService: ConfigService) {
  return () => configService.load();
}

export const ConfigServiceInitProvider = {
  provide: APP_INITIALIZER,
  useFactory: ConfigServiceInitFactory,
  deps: [ConfigService],
  multi: true
}

然后将ConfigServiceInitProvider和ConfigService(将ConfigService放在ConfigServiceInitProvider之前)一起添加到AppModule提供程序中,然后仅在需要时注入ConfigService并访问以下配置值:

then you add the ConfigServiceInitProvider to your AppModule providers along with the ConfigService (put ConfigService before ConfigServiceInitProvider) and just inject the ConfigService where needed and access the config values like:

constructor(private _config: ConfigService) {
    this.apiBase = this._config.config.api1;
}

我不喜欢_config.config的重复性,因此我通常也会在config服务上定义getter,例如:

I don't like the repetitiveness of the _config.config so i also will usually define getters on my config service like:

get api1() { return this.config.api1 }

然后您可以致电:

this.apiBase = this._config.api1;

但是,如果您要问是否可以在constants.ts文件中设置值,以便可以像这样使用它:

HOWEVER, if you're asking if it's possible to set values in a constants.ts file so that it can be used like:

import {Constants} from 'app/constants';

constructor() {
   this.apiBase = Constants.api1;
}

在运行时从服务器加载的内容无法完成,因为在运行构建命令时,所有打字稿都被编译为javascript.因此,从逻辑上讲,如果不将其作为服务值提供,则无法使用从服务器加载的内容来创建内部版本.您将始终需要注入服务.

that cannot be done with something loaded from your server at runtime, because all your typescript is compiled to javascript when you run your build commands. So you logically can't create your build with something loaded from the server without it being provided as a service value. You will always have to inject a service.

唯一的解决方法是在运行构建之前插入一个不同的常量文件,因此您无需从服务器调用配置.但这有其自身的缺点,例如,它需要完全重建并重新部署以更新配置值,这首先是针对配置的.

The only way around this is to insert a different constants file PRIOR to running your build, then you never need to call your config from your server. But this has drawbacks of it's own such as it requiring a full rebuild and redeploy to update config values which is kind of against the point of a config in the first place.

这篇关于来自服务的Angular Access数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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