[英]Angular 2+ on multiple servers
我正在尋找一種構建生產角度並能夠更改所使用的api網址的方法。
例如,具有api和有角網的第一台服務器的網址為http://test.com 。
在另一台服務器上,我將對api和angular網站使用相同的代碼,但其網址為http://test2.com 。 我知道如何解決此問題而無需重新構建api。
但是,使用Angular,我只知道如果更改URL然后為第二個服務器重建代碼,該怎么做。
有沒有辦法例如設置文件?
首先,您必須創建一個服務來管理外部配置。 我們稍后再討論,現在轉到您的app.module.ts 。
在這里,您應該首先導入服務(我將其稱為AppConfigService)
...
import { AppConfigService } from './services/app-config.service';
...
然后,在@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);
}
)
});
}
}
最后一部分可以改進很多,這只是一個簡單的例子。
最后,我們從您的組件中獲取數據,如下所示:
import {AppConfigService} from './services/app-config.service';
...
export class YourComponent {
public url: string;
constructor ( private _config: AppConfigService ) {
this.url = this._config.getParam('url1');
}
}
編輯:現在您可以擁有一個配置了應用程序的json文件,一旦投入生產,數據仍將從該文件中獲取,因此即使在生產后也可以對其進行更改
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.