在开发期间使用localhost创建到子域的href

时间:2018-03-17 00:45:39

标签: angular proxy routing localhost href

我有几个有角度的应用程序我希望有相互联系的链接。

例如在App1中我可能有以下<a href="app2.apps.com">App2</a>。这在应用程序处于活动状态时有效,但在开发期间,这不起作用,因为app2正在localhost:50001上托管。

有没有办法设置某种类型的代理来捕获我的子域并在开发过程中将它们路由到正确的localhost?

1 个答案:

答案 0 :(得分:1)

如果您使用的是angular-cli,则可以使用/src/environments下的 environment.ts 文件。

您可以在这些环境文件中定义特定于环境的值

environment.<some-environment-name>.ts

示例:

environment.prod.ts (制作环境)

export const environment = {
    production: true,
    api: {
        baseUrl: "http://app2.apps.com"
    },
    // some other properties if required
};

另一个发展对象

environment.ts (开发环境)

export const environment = {
    production: false,
    api: {
        baseUrl: "http://localhost:50001"
    },
    // some other properties if required
};

如果您还有其他环境,则可以使用其他环境文件

environment.stage.ts (暂存环境)

export const environment = {
    production: false,
    api: {
        baseUrl: "http://app2.stagingapp.com"
    },
    // some other properties if required
};

然后,在angular-cli.json属性

下的apps中声明它们
apps: {
    ..
    ..
    "environmentSource": "environments/environment.ts",  // this should be imported in all the components/services etc
    "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts",
        "stage": "environments/environment.stage.ts"
    }
}

在其他地方使用这些值(组件,服务等)

import { environment } from ../environments/environment

然后使用它

<强> foo.service.ts

private readonly API_URL = `${environment.api.baseUrl}/foo`

public getFoo() {
    return this._http.get(API_URL);
}

注意:永远不要在任何组件或服务中导入特定的环境文件,

例如,

你应该从不这样做

import { environment } from ../environments/environment.prod; // NEVER do this

而不是

使用ng serve运行时,请使用--environment--env选项指定环境值,而angular-cli将负责其余工作。

ng serve --env=prod  // uses values in environment.prod.ts
ng serve --env=stage // uses values in environment.stage.ts
ng serve             // uses values in environment.ts

执行ng build时,请使用--prod标志进行生产构建

ng build --prod

要与其他环境一起构建,您可以使用--env选项指定环境

ng build --env=stage

希望这有帮助。

相关问题