how to inject API_BASE_URL (a string) in an angular service












5















this autogenerated service (by NSwagStudio) needs an API_BASE_URL (InjectionToken) value in order to perform http requests
how and where i can inject it?



/* tslint:disable */
//----------------------
// <auto-generated>
// Generated using the NSwag toolchain v11.12.16.0 (NJsonSchema v9.10.19.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Observable';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpResponseBase, HttpErrorResponse } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable()
export class DocumentService {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "";
}

getAll(): Observable<string | null> {
let url_ = this.baseUrl + "/api/Document";
url_ = url_.replace(/[?&]$/, "");

let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json"
})
};

return this.http.request("get", url_, options_).flatMap((response_ : any) => {
return this.processGetAll(response_);
}).catch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetAll(<any>response_);
} catch (e) {
return <Observable<string | null>><any>Observable.throw(e);
}
} else
return <Observable<string | null>><any>Observable.throw(response_);
});
}

protected processGetAll(response: HttpResponseBase): Observable<string | null> {
...........code
........
....
}
}


may someone give me some super quick tips about how InjectioToken works and how inject it into this service?



Angular5 - Nswag










share|improve this question



























    5















    this autogenerated service (by NSwagStudio) needs an API_BASE_URL (InjectionToken) value in order to perform http requests
    how and where i can inject it?



    /* tslint:disable */
    //----------------------
    // <auto-generated>
    // Generated using the NSwag toolchain v11.12.16.0 (NJsonSchema v9.10.19.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
    // </auto-generated>
    //----------------------
    // ReSharper disable InconsistentNaming

    import 'rxjs/add/observable/fromPromise';
    import 'rxjs/add/observable/of';
    import 'rxjs/add/observable/throw';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/toPromise';
    import 'rxjs/add/operator/mergeMap';
    import 'rxjs/add/operator/catch';

    import { Observable } from 'rxjs/Observable';
    import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpResponseBase, HttpErrorResponse } from '@angular/common/http';

    export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

    @Injectable()
    export class DocumentService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
    this.http = http;
    this.baseUrl = baseUrl ? baseUrl : "";
    }

    getAll(): Observable<string | null> {
    let url_ = this.baseUrl + "/api/Document";
    url_ = url_.replace(/[?&]$/, "");

    let options_ : any = {
    observe: "response",
    responseType: "blob",
    headers: new HttpHeaders({
    "Content-Type": "application/json",
    "Accept": "application/json"
    })
    };

    return this.http.request("get", url_, options_).flatMap((response_ : any) => {
    return this.processGetAll(response_);
    }).catch((response_: any) => {
    if (response_ instanceof HttpResponseBase) {
    try {
    return this.processGetAll(<any>response_);
    } catch (e) {
    return <Observable<string | null>><any>Observable.throw(e);
    }
    } else
    return <Observable<string | null>><any>Observable.throw(response_);
    });
    }

    protected processGetAll(response: HttpResponseBase): Observable<string | null> {
    ...........code
    ........
    ....
    }
    }


    may someone give me some super quick tips about how InjectioToken works and how inject it into this service?



    Angular5 - Nswag










    share|improve this question

























      5












      5








      5


      1






      this autogenerated service (by NSwagStudio) needs an API_BASE_URL (InjectionToken) value in order to perform http requests
      how and where i can inject it?



      /* tslint:disable */
      //----------------------
      // <auto-generated>
      // Generated using the NSwag toolchain v11.12.16.0 (NJsonSchema v9.10.19.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
      // </auto-generated>
      //----------------------
      // ReSharper disable InconsistentNaming

      import 'rxjs/add/observable/fromPromise';
      import 'rxjs/add/observable/of';
      import 'rxjs/add/observable/throw';
      import 'rxjs/add/operator/map';
      import 'rxjs/add/operator/toPromise';
      import 'rxjs/add/operator/mergeMap';
      import 'rxjs/add/operator/catch';

      import { Observable } from 'rxjs/Observable';
      import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
      import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpResponseBase, HttpErrorResponse } from '@angular/common/http';

      export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

      @Injectable()
      export class DocumentService {
      private http: HttpClient;
      private baseUrl: string;
      protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

      constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
      this.http = http;
      this.baseUrl = baseUrl ? baseUrl : "";
      }

      getAll(): Observable<string | null> {
      let url_ = this.baseUrl + "/api/Document";
      url_ = url_.replace(/[?&]$/, "");

      let options_ : any = {
      observe: "response",
      responseType: "blob",
      headers: new HttpHeaders({
      "Content-Type": "application/json",
      "Accept": "application/json"
      })
      };

      return this.http.request("get", url_, options_).flatMap((response_ : any) => {
      return this.processGetAll(response_);
      }).catch((response_: any) => {
      if (response_ instanceof HttpResponseBase) {
      try {
      return this.processGetAll(<any>response_);
      } catch (e) {
      return <Observable<string | null>><any>Observable.throw(e);
      }
      } else
      return <Observable<string | null>><any>Observable.throw(response_);
      });
      }

      protected processGetAll(response: HttpResponseBase): Observable<string | null> {
      ...........code
      ........
      ....
      }
      }


      may someone give me some super quick tips about how InjectioToken works and how inject it into this service?



      Angular5 - Nswag










      share|improve this question














      this autogenerated service (by NSwagStudio) needs an API_BASE_URL (InjectionToken) value in order to perform http requests
      how and where i can inject it?



      /* tslint:disable */
      //----------------------
      // <auto-generated>
      // Generated using the NSwag toolchain v11.12.16.0 (NJsonSchema v9.10.19.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
      // </auto-generated>
      //----------------------
      // ReSharper disable InconsistentNaming

      import 'rxjs/add/observable/fromPromise';
      import 'rxjs/add/observable/of';
      import 'rxjs/add/observable/throw';
      import 'rxjs/add/operator/map';
      import 'rxjs/add/operator/toPromise';
      import 'rxjs/add/operator/mergeMap';
      import 'rxjs/add/operator/catch';

      import { Observable } from 'rxjs/Observable';
      import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
      import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpResponseBase, HttpErrorResponse } from '@angular/common/http';

      export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

      @Injectable()
      export class DocumentService {
      private http: HttpClient;
      private baseUrl: string;
      protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

      constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
      this.http = http;
      this.baseUrl = baseUrl ? baseUrl : "";
      }

      getAll(): Observable<string | null> {
      let url_ = this.baseUrl + "/api/Document";
      url_ = url_.replace(/[?&]$/, "");

      let options_ : any = {
      observe: "response",
      responseType: "blob",
      headers: new HttpHeaders({
      "Content-Type": "application/json",
      "Accept": "application/json"
      })
      };

      return this.http.request("get", url_, options_).flatMap((response_ : any) => {
      return this.processGetAll(response_);
      }).catch((response_: any) => {
      if (response_ instanceof HttpResponseBase) {
      try {
      return this.processGetAll(<any>response_);
      } catch (e) {
      return <Observable<string | null>><any>Observable.throw(e);
      }
      } else
      return <Observable<string | null>><any>Observable.throw(response_);
      });
      }

      protected processGetAll(response: HttpResponseBase): Observable<string | null> {
      ...........code
      ........
      ....
      }
      }


      may someone give me some super quick tips about how InjectioToken works and how inject it into this service?



      Angular5 - Nswag







      angular nswag






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 10 '18 at 7:27









      alexalex

      4911628




      4911628
























          3 Answers
          3






          active

          oldest

          votes


















          5














          On the parent module create a provider for API_BASE_URL



          export function getBaseUrl(): string {
          return AppConsts.baseUrl;
          }

          @NgModule({
          declarations: [AppComponent],
          imports: [BrowserModule],
          providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
          bootstrap: [AppComponent]
          })
          export class AppModule {}


          and then define a AppConsts class with static properties as such



          export class AppConsts {
          static baseUrl = "your_api_base_url";
          }


          Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture.
          I leave you here the url for the angular project + the url for this specific code.






          share|improve this answer
























          • getBaseUrl did the trick for me

            – bluee
            Feb 5 at 4:21











          • But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

            – Janne Harju
            Feb 10 at 11:03





















          2














          As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:



          export const environment = {

          production: false,
          apiRoot: "https://localhost:1234",
          };


          Then you can just use useValue in your provider (everything else removed for simplicity):



          ...
          import { environment } from '@env/environment';

          @NgModule({

          imports: [ ... ],

          declarations: [ ... ],

          providers: [

          {
          provide: API_BASE_URL,
          useValue: environment.apiRoot
          },
          ...
          ]

          exports: [ ... ]
          })
          export class AppModule {}


          To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:



          {
          ...
          "compilerOptions": {
          "baseUrl": "src",
          "paths": {
          "@env/*": [ "environments/*" ]
          },
          etc...
          }


          And Angular will replace the corresponding environment settings depending on the ---env flag used.






          share|improve this answer


























          • Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

            – Nico
            11 hours ago











          • Hi @Nico, have edited my answer to show where this is set up.

            – Matt
            6 hours ago





















          1














          THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:



          // environment.ts
          export const environment = {
          production: false,
          API_BASE_URL: "baseUrlOfApiForDevelopment",
          };

          // environment.prod.ts
          export const environment = {
          production: false,
          API_BASE_URL: "baseUrlOfApiForProduction",
          };


          Now you need to import in your service to use it.






          share|improve this answer























            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%2f48182290%2fhow-to-inject-api-base-url-a-string-in-an-angular-service%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5














            On the parent module create a provider for API_BASE_URL



            export function getBaseUrl(): string {
            return AppConsts.baseUrl;
            }

            @NgModule({
            declarations: [AppComponent],
            imports: [BrowserModule],
            providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
            bootstrap: [AppComponent]
            })
            export class AppModule {}


            and then define a AppConsts class with static properties as such



            export class AppConsts {
            static baseUrl = "your_api_base_url";
            }


            Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture.
            I leave you here the url for the angular project + the url for this specific code.






            share|improve this answer
























            • getBaseUrl did the trick for me

              – bluee
              Feb 5 at 4:21











            • But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

              – Janne Harju
              Feb 10 at 11:03


















            5














            On the parent module create a provider for API_BASE_URL



            export function getBaseUrl(): string {
            return AppConsts.baseUrl;
            }

            @NgModule({
            declarations: [AppComponent],
            imports: [BrowserModule],
            providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
            bootstrap: [AppComponent]
            })
            export class AppModule {}


            and then define a AppConsts class with static properties as such



            export class AppConsts {
            static baseUrl = "your_api_base_url";
            }


            Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture.
            I leave you here the url for the angular project + the url for this specific code.






            share|improve this answer
























            • getBaseUrl did the trick for me

              – bluee
              Feb 5 at 4:21











            • But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

              – Janne Harju
              Feb 10 at 11:03
















            5












            5








            5







            On the parent module create a provider for API_BASE_URL



            export function getBaseUrl(): string {
            return AppConsts.baseUrl;
            }

            @NgModule({
            declarations: [AppComponent],
            imports: [BrowserModule],
            providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
            bootstrap: [AppComponent]
            })
            export class AppModule {}


            and then define a AppConsts class with static properties as such



            export class AppConsts {
            static baseUrl = "your_api_base_url";
            }


            Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture.
            I leave you here the url for the angular project + the url for this specific code.






            share|improve this answer













            On the parent module create a provider for API_BASE_URL



            export function getBaseUrl(): string {
            return AppConsts.baseUrl;
            }

            @NgModule({
            declarations: [AppComponent],
            imports: [BrowserModule],
            providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
            bootstrap: [AppComponent]
            })
            export class AppModule {}


            and then define a AppConsts class with static properties as such



            export class AppConsts {
            static baseUrl = "your_api_base_url";
            }


            Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture.
            I leave you here the url for the angular project + the url for this specific code.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 26 '18 at 15:11









            Guido DizioliGuido Dizioli

            198211




            198211













            • getBaseUrl did the trick for me

              – bluee
              Feb 5 at 4:21











            • But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

              – Janne Harju
              Feb 10 at 11:03





















            • getBaseUrl did the trick for me

              – bluee
              Feb 5 at 4:21











            • But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

              – Janne Harju
              Feb 10 at 11:03



















            getBaseUrl did the trick for me

            – bluee
            Feb 5 at 4:21





            getBaseUrl did the trick for me

            – bluee
            Feb 5 at 4:21













            But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

            – Janne Harju
            Feb 10 at 11:03







            But if I have several different client files and sevaral API_BASE_URL variables in each files how can I set provider for each of them in one module file. There will be conflict. I tried use 'AP_BASE_URL'. And other thing is there is no need for factory. You can use useValue instead of factory. Then you can set value directly from environment or as you use AppConsts

            – Janne Harju
            Feb 10 at 11:03















            2














            As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:



            export const environment = {

            production: false,
            apiRoot: "https://localhost:1234",
            };


            Then you can just use useValue in your provider (everything else removed for simplicity):



            ...
            import { environment } from '@env/environment';

            @NgModule({

            imports: [ ... ],

            declarations: [ ... ],

            providers: [

            {
            provide: API_BASE_URL,
            useValue: environment.apiRoot
            },
            ...
            ]

            exports: [ ... ]
            })
            export class AppModule {}


            To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:



            {
            ...
            "compilerOptions": {
            "baseUrl": "src",
            "paths": {
            "@env/*": [ "environments/*" ]
            },
            etc...
            }


            And Angular will replace the corresponding environment settings depending on the ---env flag used.






            share|improve this answer


























            • Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

              – Nico
              11 hours ago











            • Hi @Nico, have edited my answer to show where this is set up.

              – Matt
              6 hours ago


















            2














            As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:



            export const environment = {

            production: false,
            apiRoot: "https://localhost:1234",
            };


            Then you can just use useValue in your provider (everything else removed for simplicity):



            ...
            import { environment } from '@env/environment';

            @NgModule({

            imports: [ ... ],

            declarations: [ ... ],

            providers: [

            {
            provide: API_BASE_URL,
            useValue: environment.apiRoot
            },
            ...
            ]

            exports: [ ... ]
            })
            export class AppModule {}


            To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:



            {
            ...
            "compilerOptions": {
            "baseUrl": "src",
            "paths": {
            "@env/*": [ "environments/*" ]
            },
            etc...
            }


            And Angular will replace the corresponding environment settings depending on the ---env flag used.






            share|improve this answer


























            • Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

              – Nico
              11 hours ago











            • Hi @Nico, have edited my answer to show where this is set up.

              – Matt
              6 hours ago
















            2












            2








            2







            As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:



            export const environment = {

            production: false,
            apiRoot: "https://localhost:1234",
            };


            Then you can just use useValue in your provider (everything else removed for simplicity):



            ...
            import { environment } from '@env/environment';

            @NgModule({

            imports: [ ... ],

            declarations: [ ... ],

            providers: [

            {
            provide: API_BASE_URL,
            useValue: environment.apiRoot
            },
            ...
            ]

            exports: [ ... ]
            })
            export class AppModule {}


            To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:



            {
            ...
            "compilerOptions": {
            "baseUrl": "src",
            "paths": {
            "@env/*": [ "environments/*" ]
            },
            etc...
            }


            And Angular will replace the corresponding environment settings depending on the ---env flag used.






            share|improve this answer















            As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:



            export const environment = {

            production: false,
            apiRoot: "https://localhost:1234",
            };


            Then you can just use useValue in your provider (everything else removed for simplicity):



            ...
            import { environment } from '@env/environment';

            @NgModule({

            imports: [ ... ],

            declarations: [ ... ],

            providers: [

            {
            provide: API_BASE_URL,
            useValue: environment.apiRoot
            },
            ...
            ]

            exports: [ ... ]
            })
            export class AppModule {}


            To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:



            {
            ...
            "compilerOptions": {
            "baseUrl": "src",
            "paths": {
            "@env/*": [ "environments/*" ]
            },
            etc...
            }


            And Angular will replace the corresponding environment settings depending on the ---env flag used.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 6 hours ago

























            answered Nov 24 '18 at 6:23









            MattMatt

            4,38432426




            4,38432426













            • Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

              – Nico
              11 hours ago











            • Hi @Nico, have edited my answer to show where this is set up.

              – Matt
              6 hours ago





















            • Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

              – Nico
              11 hours ago











            • Hi @Nico, have edited my answer to show where this is set up.

              – Matt
              6 hours ago



















            Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

            – Nico
            11 hours ago





            Hi Matt, When I try to implement your code, API_BASE_URL is of course undefined and it's not possible to compile. Where should I import it from? Thanks

            – Nico
            11 hours ago













            Hi @Nico, have edited my answer to show where this is set up.

            – Matt
            6 hours ago







            Hi @Nico, have edited my answer to show where this is set up.

            – Matt
            6 hours ago













            1














            THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:



            // environment.ts
            export const environment = {
            production: false,
            API_BASE_URL: "baseUrlOfApiForDevelopment",
            };

            // environment.prod.ts
            export const environment = {
            production: false,
            API_BASE_URL: "baseUrlOfApiForProduction",
            };


            Now you need to import in your service to use it.






            share|improve this answer




























              1














              THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:



              // environment.ts
              export const environment = {
              production: false,
              API_BASE_URL: "baseUrlOfApiForDevelopment",
              };

              // environment.prod.ts
              export const environment = {
              production: false,
              API_BASE_URL: "baseUrlOfApiForProduction",
              };


              Now you need to import in your service to use it.






              share|improve this answer


























                1












                1








                1







                THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:



                // environment.ts
                export const environment = {
                production: false,
                API_BASE_URL: "baseUrlOfApiForDevelopment",
                };

                // environment.prod.ts
                export const environment = {
                production: false,
                API_BASE_URL: "baseUrlOfApiForProduction",
                };


                Now you need to import in your service to use it.






                share|improve this answer













                THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:



                // environment.ts
                export const environment = {
                production: false,
                API_BASE_URL: "baseUrlOfApiForDevelopment",
                };

                // environment.prod.ts
                export const environment = {
                production: false,
                API_BASE_URL: "baseUrlOfApiForProduction",
                };


                Now you need to import in your service to use it.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 10 '18 at 7:33









                Sandip JaiswalSandip Jaiswal

                1,4571612




                1,4571612






























                    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%2f48182290%2fhow-to-inject-api-base-url-a-string-in-an-angular-service%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







                    Popular posts from this blog

                    Wiesbaden

                    Marschland

                    Dieringhausen