[英]Angular 6 : How do I set production and development base url
New to angular I want to set different base url for production and development. Angular 新手我想为生产和开发设置不同的基本 url。 I want to dynamically set it so that to reduce the pain of hard-coding in index.html while switching between production and development
我想动态设置它,以减少在生产和开发之间切换时在 index.html 中进行硬编码的痛苦
<!-- Production url will be as below--> <base url="/prod/" /> <!-- Development url will be as below--> <base url="/dev/" />
You can use environments.ts , environment.prod.ts
files at build(dev) time you will got environments.ts and production time you will be using environment.prod.ts您可以在构建(开发)时使用
environments.ts , environment.prod.ts
文件,您将获得 environment.ts 和生产时您将使用 environment.prod.ts
and you can setup your own configuration ⚙你可以设置自己的配置⚙
Development 🏗发展🏗
export const environment = {
production: false ,
url : '127.0.0.1:4200/api'
};
Production 🚀生产🚀
export const environment = {
production: true,
url : 'production.com/api'
};
app.component应用程序组件
import { environment } from "../environments/environment";
export class AppComponent {
ngOnInit() {
console.log(environment.url);
}
}
the console output will be 127.0.0.1:4200/api
if you run ng s
and production.com/api
in case you run ng s --prod
如果您运行
ng s
,控制台输出将为127.0.0.1:4200/api
,如果您运行ng s --prod
production.com/api
When you build for production ng build --prod
the environment.ts will be the content of environment.prod.ts
当您为生产
ng build --prod
时 environment.ts 将是environment.prod.ts
的内容
For delevopment you can set this in environment.ts file.对于开发,您可以在 environment.ts 文件中进行设置。 Like that
像那样
export const environment = {
production: false,
baseUrl: 'http://test.net/api'
};
and for production in environment.prod.ts并用于 environment.prod.ts 中的生产
export const environment = {
production: true,
baseUrl: 'https://prod.net/api'
};
Then you should use url in your services like that然后你应该像这样在你的服务中使用 url
@Injectable()
export class DataService {
baseUrl = environment.baseUrl;
constructor(private httpClient: HttpClient) { }
getData(id: number) {
let url = this.baseUrl + '/data/1';
return this.httpClient.get<JSON>(url);
}
}
you need to have at least two typescript files in your angular project.您需要在 Angular 项目中至少有两个打字稿文件。 environment.ts and environment.prod.ts.
environment.ts 和 environment.prod.ts。 For development you have to use the simple ng serve and for production you have to build and specify that you need the url from production to be used.
对于开发,您必须使用简单的 ng serve;对于生产,您必须构建并指定您需要使用生产中的 url。
To do that use: "ng build --prod."为此,请使用:“ng build --prod”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.