Angular 角度2+;在多台服务器上
我正在寻找一种方法,以建立一个生产角度,并能够改变api的url使用 例如,带有api和angular web的第一台服务器具有url 在另一台服务器上,我将对api和angular web使用相同的代码,但它有url。我知道如何在不重建api的情况下修复它 但是对于Angular,我只知道如果我更改了url,然后为第二台服务器重新生成代码,该怎么做Angular 角度2+;在多台服务器上,angular,Angular,我正在寻找一种方法,以建立一个生产角度,并能够改变api的url使用 例如,带有api和angular web的第一台服务器具有url 在另一台服务器上,我将对api和angular web使用相同的代码,但它有url。我知道如何在不重建api的情况下修复它 但是对于Angular,我只知道如果我更改了url,然后为第二台服务器重新生成代码,该怎么做 例如,有没有办法使用设置文件来实现这一点?首先,您必须创建一个服务来管理外部配置。我们稍后再讨论 现在让我们转到你的app.module.ts 在
例如,有没有办法使用设置文件来实现这一点?首先,您必须创建一个服务来管理外部配置。我们稍后再讨论 现在让我们转到你的app.module.ts 在这里,您应该首先导入服务(我将其称为AppConfigService) 然后,在@NgModule之前,您必须导出一个将初始化所有配置的函数:
export function initializeConfig( config: AppConfigService ) {
return () => config.load();
}
现在,让我们将其添加到NgModule提供程序中:
...
@NgModule({
declarations: [ ... ],
imports: [ ... ],
providers: [
...
AppConfigService, {
provide: APP_INITIALIZER,
useFactory: initializeConfig,
deps: [ AppConfigService ],
multi: true
},
...
],
bootstrap: [AppComponent]
})
...
现在让我们来看看我们之前提到的服务:
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {Observable, throwError} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private config: Object;
constructor(
private _http: HttpClient
) {
this.config = {};
}
public getParam(key: any) {
// Returns a specific parameter
if (this.config[key]) {
return this.config[key];
} else if (!key) {
return this.config;
}
return false;
}
public load(): Promise<any> {
// This will load all the parameters
const confFile = 'path-to-your-json-file';
return new Promise((resolve, reject) => {
this._http.get(confFile).subscribe(
res => {
this.config = res;
resolve(true);
},
err => {
this.config = {};
reject(err);
}
)
});
}
}
编辑:
现在,您可以使用json文件配置您的应用程序,一旦它投入生产,数据仍将从此文件中获取,因此即使在生产后,您也可以对其进行更改您可以使用环境文件构建具有专用参数的应用程序实例。如果您想在构建后执行此操作,则需要某种机制(例如用户可以切换的开关)来更改URL.Perfekt!非常感谢。
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {Observable, throwError} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private config: Object;
constructor(
private _http: HttpClient
) {
this.config = {};
}
public getParam(key: any) {
// Returns a specific parameter
if (this.config[key]) {
return this.config[key];
} else if (!key) {
return this.config;
}
return false;
}
public load(): Promise<any> {
// This will load all the parameters
const confFile = 'path-to-your-json-file';
return new Promise((resolve, reject) => {
this._http.get(confFile).subscribe(
res => {
this.config = res;
resolve(true);
},
err => {
this.config = {};
reject(err);
}
)
});
}
}
import {AppConfigService} from './services/app-config.service';
...
export class YourComponent {
public url: string;
constructor ( private _config: AppConfigService ) {
this.url = this._config.getParam('url1');
}
}