簡體   English   中英

從 Angular 服務中的 .NET appSettings.json 文件讀取環境變量?

[英]Read an environment variable from a .NET appSettings.json file in an Angular service?

我有一個從 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());
    }
}

我想避免在構造函數中硬編碼 API 地址,而是從appSettings.json讀取設置,我可以在啟動時用於生產和本地主機服務器的操作 URL。

在 ASP.NET MVC Core 中執行此操作的最佳方法是什么?

我能想到的兩種選擇:

1) 將配置放在environment.tsappSettings.json - appSettings.json訪問內置於 angular 中。

2) 服務的第 1 步使用直接的http.get加載appSettings.json ,然后使用其中的配置加載所需的數據。

environment.ts 示例

export const environment = {
    apiUrl: 'http://api.dc-shop.com',
    mode: 'prod'
};

用法示例:

import { environment } from './environment';    
constructor(private _http: Http) {
    this.actionUrl = environment.apiUrl + '/review';
}

您可以使用Angular Http Intercepter來實現這一點

在每個請求中添加http://api.dc-shop.com前綴。

示例代碼:

在你的 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);
    }


}

在您的主模塊中:

   export const httpInterceptorProviders = [
      {provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true},
    } 

   @NgModule({
       providers: [...,httpInterceptorProviders]
    })

如果你想在不同的環境中配置你的前綴 url:

您可以在/src/environments下的environment.xx.ts定義它

並在 angular.json 中定義構建配置

 ....
 "configurations": {
   "api": {
    ....
       "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.api.ts"
            }
          ]
     }
   ....
 }
 ...

當你構建你的應用程序時,

只需添加配置

 ng build   --configuration=api

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM