[英]Read an environment variable from a .NET appSettings.json file in an Angular service?
I have a service which requests some JSON data from a Web API:我有一个从 Web API 请求一些 JSON 数据的服务:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ReviewService {
private actionUrl: string;
constructor(private _http: Http) {
this.actionUrl = 'http://api.dc-shop.com/review';
}
public GetAll = (): any => {
return this._http.get(this.actionUrl)
.map(x => x.json());
}
}
I would like to avoid hard coding the API address in the constructor and instead read a setting from appSettings.json
which I can use for the action URL at startup for production and localhost servers.我想避免在构造函数中硬编码 API 地址,而是从appSettings.json
读取设置,我可以在启动时用于生产和本地主机服务器的操作 URL。
What is the best way of doing this in ASP.NET MVC Core?在 ASP.NET MVC Core 中执行此操作的最佳方法是什么?
Two options I can think of:我能想到的两种选择:
1) Put the configuration in environment.ts
as well as appSettings.json
- access to this is built into angular. 1) 将配置放在environment.ts
和appSettings.json
- appSettings.json
访问内置于 angular 中。
2) Step 1 of your service loads appSettings.json
using a straight-forward http.get
and then uses the config from it load the required data. 2) 服务的第 1 步使用直接的http.get
加载appSettings.json
,然后使用其中的配置加载所需的数据。
Example of environment.ts environment.ts 示例
export const environment = {
apiUrl: 'http://api.dc-shop.com',
mode: 'prod'
};
Example usage:用法示例:
import { environment } from './environment';
constructor(private _http: Http) {
this.actionUrl = environment.apiUrl + '/review';
}
You can implement this by using Angular Http Intercepter您可以使用Angular Http Intercepter来实现这一点
Add the http://api.dc-shop.com prefix in each request.在每个请求中添加http://api.dc-shop.com前缀。
Example Code:示例代码:
Write an Request Intercepter in Your Angular App:在你的 Angular 应用中编写一个请求拦截器:
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let req_url = req.url
req.clone({url:`http://api.dc-shop.com/${req_url}`})
return next.handle(req);
}
}
And in your Main Module:在您的主模块中:
export const httpInterceptorProviders = [
{provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true},
}
@NgModule({
providers: [...,httpInterceptorProviders]
})
If you want to config your prefix url in different environment:如果你想在不同的环境中配置你的前缀 url:
Your can define it in your environment.xx.ts
under /src/environments
您可以在/src/environments
下的environment.xx.ts
定义它
And Define the build config in angular.json并在 angular.json 中定义构建配置
....
"configurations": {
"api": {
....
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.api.ts"
}
]
}
....
}
...
And when your build your app ,当你构建你的应用程序时,
just add configuration只需添加配置
ng build --configuration=api
Good Luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.