如何在Angular中读取当前的网址

时间:2019-11-14 17:04:31

标签: angular

我在编程方面还很陌生,我的经理要求我做我不知道该怎么做的事情。我需要创建一个将读取URL的函数,从而知道正在构建哪个环境。然后,该函数应在load函数中插入正确的环境,该函数现在具有以下代码:

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 json文件来更改加载功能:

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

这有意义吗?谁能帮我吗?

3 个答案:

答案 0 :(得分:1)

使用Angular Router类获取当前URL:

currentUrl: string;

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

答案 1 :(得分:0)

load() {
        // const jsonFile = `assets/config/config.${environment.name}.json`;
      this.configEnv()
      const jsonFile = `assets/config/config.${this.currentEnv}.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);
            });
        });
    }


    configEnv() {
          this.currentUrl = window.location.hostname;
          if(this.currentUrl.includes('local')) {
            this.currentEnv = 'local'
          } else if (this.currentUrl.includes('prd')) {
            this.currentEnv = 'prod'
          } else if (this.currentUrl.includes('dev')) {
            this.currentEnv = 'dev'
          } else {console.log('no environment found!')}

          console.log(this.currentUrl);
        }

答案 2 :(得分:0)

Text