首页 > 解决方案 > 如何在 Angular 中读取当前 URL

问题描述

我是编程新手,我的经理让我做一些我真的不知道该怎么做的事情。我需要创建一个函数来读取 URL,从而知道正在构建哪个环境。然后该函数应在加载函数中插入正确的环境,该函数现在具有以下代码:

load() {
    const jsonFile = `assets / config / config.$ {
        environment.name
    }.json`;
    console.log(`Loading file $ {
        jsonFile
    }`)
    return new Promise < void > ((resolve, reject) = > {
            this.http.get(jsonFile).toPromise().then((response: IAppConfig) = > {
                    AppConfig.settings = <IAppConfig>response;
               resolve();
            }).catch((response: any) => {
               reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
               console.log(jsonFile);
            });
        });
    }

谁能告诉我如何提取当前网址?一旦我有了它,我的函数将如下所示:

configUrl() {
var currentUrl =

然后,我将通过用以下内容替换当前的 const jsonfile 来更改加载函数:

const jsonFile = assets/config/config.${currentUrl.name}.json;

这有意义吗?谁能帮我?

标签: angular

解决方案


使用 Angular Router 类获取当前 URL:

currentUrl: string;

constructor(private router: Router){
    this.currentUrl = this.router.url;
    this.load();
}

推荐阅读