How can I read an environment variable from a .NET appSettings.json file in an Angular service?










1















I'm new to Angular2 and have some questions.



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?










share|improve this question
























  • Yes, I have a appSettings.json file in my MVC project where I define the API address so that I can test it on localhost

    – loz
    Nov 13 '18 at 9:12











  • Why not to store this in some global service? and call every time from there

    – Pardeep Jain
    Nov 13 '18 at 9:13












  • Thanks for that link I can see having a separate Angular2 environment file would work.

    – loz
    Nov 13 '18 at 9:14











  • Thanks Dale that has answered my question.

    – loz
    Nov 13 '18 at 9:26















1















I'm new to Angular2 and have some questions.



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?










share|improve this question
























  • Yes, I have a appSettings.json file in my MVC project where I define the API address so that I can test it on localhost

    – loz
    Nov 13 '18 at 9:12











  • Why not to store this in some global service? and call every time from there

    – Pardeep Jain
    Nov 13 '18 at 9:13












  • Thanks for that link I can see having a separate Angular2 environment file would work.

    – loz
    Nov 13 '18 at 9:14











  • Thanks Dale that has answered my question.

    – loz
    Nov 13 '18 at 9:26













1












1








1








I'm new to Angular2 and have some questions.



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?










share|improve this question
















I'm new to Angular2 and have some questions.



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?







asp.net-mvc angular angular-services






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 9:29







loz

















asked Nov 13 '18 at 9:07









lozloz

3817




3817












  • Yes, I have a appSettings.json file in my MVC project where I define the API address so that I can test it on localhost

    – loz
    Nov 13 '18 at 9:12











  • Why not to store this in some global service? and call every time from there

    – Pardeep Jain
    Nov 13 '18 at 9:13












  • Thanks for that link I can see having a separate Angular2 environment file would work.

    – loz
    Nov 13 '18 at 9:14











  • Thanks Dale that has answered my question.

    – loz
    Nov 13 '18 at 9:26

















  • Yes, I have a appSettings.json file in my MVC project where I define the API address so that I can test it on localhost

    – loz
    Nov 13 '18 at 9:12











  • Why not to store this in some global service? and call every time from there

    – Pardeep Jain
    Nov 13 '18 at 9:13












  • Thanks for that link I can see having a separate Angular2 environment file would work.

    – loz
    Nov 13 '18 at 9:14











  • Thanks Dale that has answered my question.

    – loz
    Nov 13 '18 at 9:26
















Yes, I have a appSettings.json file in my MVC project where I define the API address so that I can test it on localhost

– loz
Nov 13 '18 at 9:12





Yes, I have a appSettings.json file in my MVC project where I define the API address so that I can test it on localhost

– loz
Nov 13 '18 at 9:12













Why not to store this in some global service? and call every time from there

– Pardeep Jain
Nov 13 '18 at 9:13






Why not to store this in some global service? and call every time from there

– Pardeep Jain
Nov 13 '18 at 9:13














Thanks for that link I can see having a separate Angular2 environment file would work.

– loz
Nov 13 '18 at 9:14





Thanks for that link I can see having a separate Angular2 environment file would work.

– loz
Nov 13 '18 at 9:14













Thanks Dale that has answered my question.

– loz
Nov 13 '18 at 9:26





Thanks Dale that has answered my question.

– loz
Nov 13 '18 at 9:26












2 Answers
2






active

oldest

votes


















1














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';






share|improve this answer




















  • 1





    I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

    – loz
    Nov 13 '18 at 12:11


















1














You can implement this by using Angular Http Intercepter



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



Example Code:



Write an 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


Good Luck!






share|improve this answer

























  • Better would be If you provide example too.

    – Pardeep Jain
    Nov 13 '18 at 9:14











  • I think api doc's examples are very clear now

    – junk
    Nov 13 '18 at 9:17











  • meta.stackexchange.com/questions/8231/…

    – Dale Burrell
    Nov 13 '18 at 9:18











  • I have updated my answer now

    – junk
    Nov 13 '18 at 9:38










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53277368%2fhow-can-i-read-an-environment-variable-from-a-net-appsettings-json-file-in-an-a%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














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';






share|improve this answer




















  • 1





    I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

    – loz
    Nov 13 '18 at 12:11















1














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';






share|improve this answer




















  • 1





    I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

    – loz
    Nov 13 '18 at 12:11













1












1








1







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';






share|improve this answer















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';







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 14:11









loz

3817




3817










answered Nov 13 '18 at 9:29









Dale BurrellDale Burrell

2,93432348




2,93432348







  • 1





    I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

    – loz
    Nov 13 '18 at 12:11












  • 1





    I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

    – loz
    Nov 13 '18 at 12:11







1




1





I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

– loz
Nov 13 '18 at 12:11





I ended up going for option 1 and having a separate environment.ts. The appsettings.json file is not copied to wwwroot and could contain connection strings so it was not the best solution for me.

– loz
Nov 13 '18 at 12:11













1














You can implement this by using Angular Http Intercepter



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



Example Code:



Write an 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


Good Luck!






share|improve this answer

























  • Better would be If you provide example too.

    – Pardeep Jain
    Nov 13 '18 at 9:14











  • I think api doc's examples are very clear now

    – junk
    Nov 13 '18 at 9:17











  • meta.stackexchange.com/questions/8231/…

    – Dale Burrell
    Nov 13 '18 at 9:18











  • I have updated my answer now

    – junk
    Nov 13 '18 at 9:38















1














You can implement this by using Angular Http Intercepter



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



Example Code:



Write an 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


Good Luck!






share|improve this answer

























  • Better would be If you provide example too.

    – Pardeep Jain
    Nov 13 '18 at 9:14











  • I think api doc's examples are very clear now

    – junk
    Nov 13 '18 at 9:17











  • meta.stackexchange.com/questions/8231/…

    – Dale Burrell
    Nov 13 '18 at 9:18











  • I have updated my answer now

    – junk
    Nov 13 '18 at 9:38













1












1








1







You can implement this by using Angular Http Intercepter



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



Example Code:



Write an 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


Good Luck!






share|improve this answer















You can implement this by using Angular Http Intercepter



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



Example Code:



Write an 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


Good Luck!







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 9:37

























answered Nov 13 '18 at 9:11









junkjunk

236417




236417












  • Better would be If you provide example too.

    – Pardeep Jain
    Nov 13 '18 at 9:14











  • I think api doc's examples are very clear now

    – junk
    Nov 13 '18 at 9:17











  • meta.stackexchange.com/questions/8231/…

    – Dale Burrell
    Nov 13 '18 at 9:18











  • I have updated my answer now

    – junk
    Nov 13 '18 at 9:38

















  • Better would be If you provide example too.

    – Pardeep Jain
    Nov 13 '18 at 9:14











  • I think api doc's examples are very clear now

    – junk
    Nov 13 '18 at 9:17











  • meta.stackexchange.com/questions/8231/…

    – Dale Burrell
    Nov 13 '18 at 9:18











  • I have updated my answer now

    – junk
    Nov 13 '18 at 9:38
















Better would be If you provide example too.

– Pardeep Jain
Nov 13 '18 at 9:14





Better would be If you provide example too.

– Pardeep Jain
Nov 13 '18 at 9:14













I think api doc's examples are very clear now

– junk
Nov 13 '18 at 9:17





I think api doc's examples are very clear now

– junk
Nov 13 '18 at 9:17













meta.stackexchange.com/questions/8231/…

– Dale Burrell
Nov 13 '18 at 9:18





meta.stackexchange.com/questions/8231/…

– Dale Burrell
Nov 13 '18 at 9:18













I have updated my answer now

– junk
Nov 13 '18 at 9:38





I have updated my answer now

– junk
Nov 13 '18 at 9:38

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53277368%2fhow-can-i-read-an-environment-variable-from-a-net-appsettings-json-file-in-an-a%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

Museum of Modern and Contemporary Art of Trento and Rovereto