lschmid
lschmid

Reputation: 183

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:

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.

What is the best way of doing this in ASP.NET MVC Core?

Upvotes: 1

Views: 1906

Answers (2)

junk
junk

Reputation: 987

You can implement this by using Angular Http Intercepter

Add the http://api.dc-shop.com prefix in each request.

Example Code:

Write a Request Intercepter in your Angular app:

@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:

Your can define it in your environment.xx.ts under /src/environments

And define the build config in 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

Upvotes: 1

Dale K
Dale K

Reputation: 27201

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.

  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.

Example of 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';
}

Upvotes: 2

Related Questions