[英]Can I retrieve the --base-href parameter value in my code when building an Angular project?
對於我的 Angular 項目,我有多個環境,每個環境都用於特定的DTAP階段。 在構建這個 Angular 項目時,我將 --base-href 標志設置為相應的基本 URL。 但是,我的代碼中還設置了一個 URL,該 URL 屬於要與之對應的第二個 Web 服務器。 此 Web 服務器還具有多個 DTAP 階段。 因此,我希望能夠在我的代碼中“知道”哪個 --base-url 標志值設置為能夠將變量設置為第二個 Web 服務器的相應 URL。
由於我找不到有關此主題的任何內容,因此我無法取得任何成功。 現在我已經設置好了,所以我必須手動更改變量的值。 但我想擺脫這種做法,因為在構建項目時很容易忘記它。
這個想法是必須遵循以下代碼:
let url;
if (base-href.contains('test'))
url = 'https://test.com';
else if (base-href.contains('acceptance'))
url = 'https://acceptance.com'
else if (base-href.contains('deployment'))
url = 'https://deployment.com'
// Send API call to URL
我用來構建的 URL 是固定的,所以我知道其中的文本是什么,以便我可以確保第二個 Web 服務器的 URL 始終設置正確。
如果有人能指出我正確的方向來實現這一目標,將不勝感激!
您可以將另一個變量添加到您的environment.ts
。 編譯時,將根據環境設置該值,從而允許在代碼中引用該變量。
export const environment = {
production: true,
host: 'test'
};
在您的組件中:
import { environment } from '../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
if (environment.host == 'test') {
// whaever
}
}
}
更好的方法是,在應用加載時調用http請求,獲取純json文件/ db記錄,並將這些設置保存在服務器上。 這樣,您就可以復制粘貼經過測試驗證的代碼,直接將其粘貼到生產環境中(不包括json文件),並且可以正常工作。
在以下位置了解更多信息: Dave M Bush的文章-哪里存儲角度配置
最后,這個問題的解決方案確實很簡單,並且不一定與--base-href有關。
我不是通過在構建Angular項目時查找--base-href而是通過在應用程序已經運行時查看URL來解決此問題的:
public static url: string = location.href.indexOf('test') > -1 // Test environment
|| location.href.indexOf('localhost') > -1 // Local environment
? 'https://test.com'
: location.href.indexOf('staging') > -1 // Staging environment
? 'https://staging.com'
: location.href.indexOf('demo') > -1 // Demo environment
? 'https://demo.com'
: 'https://deployment.com'; // Deployment environment
由於這些URL將是靜態的並且不會更改,因此我確信這些設置足以查看需要使用哪個URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.