我查看了所有解决方案,并创建了一个在 Azure 和本地计算机(本地主机)上运行的解决方案。这取决于构建 - prod
(从天蓝色读取)或dev
(从本地资产文件夹读取)天蓝色插槽。
也许它对某人有帮助。
首先,您需要像Aaron Chen
提到的那样添加这个小 php 文件。在src
文件夹下的 Angular 结构中:
src/appSettings.php
$appSettings = [];
foreach ($_SERVER as $key => $value) {
if(preg_match('/^APPSETTING_/', $key)) {
$appSettings[str_replace('APPSETTING_', '', $key)] = $value;
}
}
header('Content-Type: application/json');
echo json_encode($appSettings, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
需要修改angular.json
文件。您需要添加assets
到"src/appSettings.php"
"assets": [
"src/favicon.ico",
"src/assets",
"src/appSettings.php"
],
此解决方案从链接中的 azure 获取所有配置http://<websitename>.azurewebsites.net/appSettings.php
。这仅在 Azure 中有效(需要身份验证)。对于本地开发,您需要创建一个 Json 文件,其中包含该src/assets
文件夹下的所有 Azure 插槽。
`assets/config/backend.json`;
要加载 Json 需要创建的配置
src/app/app.config.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';
import { AppSettings } from './models/AppSettings.model';
import { environment } from 'src/environments/environment';
@Injectable()
export class AppConfig {
static appSettings: AppSettings;
private http: HttpClient;
constructor( handler: HttpBackend) {
this.http = new HttpClient(handler);
}
public load() {
let backendConfigUrl: string;
if (environment.production) {
backendConfigUrl = window.location.origin + '/appsettings.php';
} else {
backendConfigUrl = `assets/config/backend.json`;
}
console.log(backendConfigUrl);
return new Promise<void>((resolve, reject) => {
this.http.get<AppSettings>(backendConfigUrl).toPromise().then((response: AppSettings) => {
AppConfig.appSettings = response;
resolve();
}).catch((response: any) => {
reject(`Could not load file ${backendConfigUrl}: ${JSON.stringify(response)}`);
});
});
}
}
然后修改src/app/app.module.ts
以在应用程序启动之前加载配置。
export function initializeApp(appConfig: AppConfig) {
return () => appConfig.load().then(() => {
console.log(AppConfig.appSettings)
});
}
providers: [
AppConfig,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [AppConfig],
multi: true
},
]
从本地文件夹ng build
加载配置。assets
从ng build --prod
Azure 读取配置。ng serve
和_ng serve --prod