简体   繁体   English

从 Angular 服务中的 .NET appSettings.json 文件读取环境变量?

[英]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.tsappSettings.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.

相关问题 .Net Core Cant从appsettings.json中读取连接字符串 - .Net Core Cant read connection string from appsettings.json Application Insights ASP.NET核心环境appsettings.json - Application Insights ASP.NET Core Environment appsettings.json appsettings.json 文件在工作时会被 ASP.NET Core 读取多少次? - How many time appsettings.json file will be read by ASP.NET Core when its working? 从appsettings.json检索数据 - Retrieving data from appsettings.json asp.net 5(mvc6配置)未从appsettings.json中读取 - asp.net 5 (mvc6 configuration) not reading from appsettings.json .NET Core 2.x从dbcontext类中的appsettings.json获取连接字符串 - .NET Core 2.x get connection string from appsettings.json in dbcontext class 如何将 Azure 服务调用添加到 appsettings.json - How to add Azure service call to appsettings.json 使用.gitignore文件隐藏appsettings.json实际上并没有隐藏 - Using .gitignore file to hide appsettings.json does not actually hide it connectionString 是否通过使用 singleton 模式从 appsettings.json 获得保护? - Is connectionString secured from appsettings.json by using singleton pattern? appsettings.Production.json具有来自appsettings.json之后的值 - appsettings.Production.json has values from appsettings.json afte publishing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM